0% found this document useful (0 votes)
12 views48 pages

Unit 4

This document covers various aspects of mobile operating systems, specifically focusing on Android fragments, their lifecycle, and interactions. It discusses creating and managing fragments, using dialogs, implementing action bars, and the role of services in Android applications. Key topics include fragment transactions, communication between fragments, and the differences between toasts and alert dialogs.

Uploaded by

aji m
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views48 pages

Unit 4

This document covers various aspects of mobile operating systems, specifically focusing on Android fragments, their lifecycle, and interactions. It discusses creating and managing fragments, using dialogs, implementing action bars, and the role of services in Android applications. Key topics include fragment transactions, communication between fragments, and the differences between toasts and alert dialogs.

Uploaded by

aji m
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

BCS6B13

Mobile Operating System


Unit 4
Contents
• Fragments in android - structure of fragment, fragment life cycle,
fragment transaction and back stack, fragment manager, saving
fragment state, communications with fragments, startActivity() and
setTargetFragment().
• Using dialogs in android, alert dialog, dialog fragments, working with
toast.
• Implementing action bar – creating action bar, types – standard action
bar, tabbed action bar activity, tabbed listener, list navigation action bar
activity, list listener, action bar and menu interaction, action bar and
search view, action bar and fragments.
• Introduction to services, bound and unbound service, life cycle of
service.
Fragments
• A Fragment represents a reusable
portion of UI.
• A fragment defines and manages
its own layout, has its own
lifecycle, and can handle its own
input events.
• Fragments cannot live on their
own--they must be hosted by an
activity or another fragment.
• Supports : modularity and
reusability
• Honeycomb – API 11
• A fragment has its own layout and its own behavior with its own life
cycle callbacks.
• You can add or remove fragments in an activity while the activity is
running.
• You can combine multiple fragments in a single activity to build a
multi-pane UI.
• A fragment can be used in multiple activities.
• Fragment life cycle is closely related to the life cycle of its host activity
which means when the activity is paused, all the fragments available in
the activity will also be stopped.
• A fragment can implement a behavior that has no user interface
component.
Life Cycle
onAttach()
• The fragment instance is associated with an activity instance.
• The fragment and the activity is not fully initialized.
• uses the fragment for further initialization work.
onCreate()
• The system calls this method when creating the fragment. You should initialize
essential components of the fragment that you want to retain when the fragment
is paused or stopped, then resumed.
onCreateView()
• The system calls this callback when it's time for the fragment to draw its user
interface for the first time. To draw a UI for your fragment, you must return a View
component from this method that is the root of your fragment's layout. You can
return null if the fragment does not provide a UI.
onActivityCreated()
• The onActivityCreated() is called after the onCreateView() method when the host
activity is created. Activity and fragment instance have been created as well as the
view hierarchy of the activity. At this point, view can be accessed with the
findViewById() method. example. In this method you can instantiate objects which
require a Context object
onStart()
• The onStart() method is called once the fragment gets visible.
onResume()
• Fragment becomes active.
onPause()
• The system calls this method as the first indication that the user is leaving
the fragment. This is usually where you should commit any changes that
should be persisted beyond the current user session.
onStop()
• Fragment going to be stopped by calling onStop()
onDestroyView()
• Fragment view will destroy after call this method
onDestroy()
• onDestroy() called to do final clean up of the fragment's state but Not
guaranteed to be called by the Android platform.
Creating Fragments
• Fragments are sub activity or a part of activity.
• Steps to create a fragment:
1. Create a layout with required controls
2. Create a class that inherits the Fragment class and attach the layout inside
the onCreateView() method.

Class F1 extends Fragment{


public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle si)
{
return inflater.inflate(R.layout.frag1,container,false);
}
}
3. Create fragments in main activity and attach the classes (created in step 2)
Fragment Manager
• The class responsible for accessing and managing fragments belonging to
an activity.
• Responsibilities of a fragment manager includes the following
• Accessing the fragments of an activity.
getFragmentById() or getFragmentByTag()
• Retrieve the fragments from the back stack when user press back button.
popBackStack().
• Register listeners to track changes in the back stack
• Helps in Debugging and logging
Fragment Transaction
• FragmentManager fragmentManager =
getSupportFragmentManager();
• FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();

• add(), remove(), replace(), detach(), addToBackStack() etc.


• At the end of each transaction, a commit() is performed
FragmentManager fm= getFragmentManager();
FragmentTransaction ft= fm.beginTransaction();
if(v.getId() == R.id.b1) {
F2 f = new F2();
ft.replace(R.id.f2, f);
}
else if(v.getId() == R.id.b2) {
F3 f = new F3();
ft.replace(R.id.f2, f);
}
ft.commit();
Fragment Communication
• Fragment can access the activity with the help of getActivity() method. With
this activity instance, its views can be accessed as follows.

TextView tv = (TextView) getActivity().findViewById(R.id.textView1);


EditText ed = (EditText) getActivty().findViewBYId(R.id.ed1);
Sring s = Ed.getText().toString();
• The fragment can access other fragments through fragmentManager class as
• MyFragment fr=
(MyFragment) getFragmentManager().findFragmentById(R.id.frag2);
Saving the state of a Fragment
• To store the internal state of a fragment override the onSaveInstanceState() method.
• Data of any type can be loaded to the parameter available using the putTYPE(String
key, TYPE val); where TYPE is any data type.

@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putByte("byte", bval);
outState.putChar("chars",cval);
outState.putInt("integer", intval);
outState.putString("str", sval);
outState.putBundle("bundle", bundleval);
}
• The values can be retrieved using getTYPE (String key) method.

@Override
public void onViewStateRestored(@Nullable Bundle s1) {
super.onViewStateRestored(savedInstanceState);
Byte bval = savedInstanceState.getByte("byte");
String nane = s1.getString(“name”); int age = s1.getInt(“age”);
Bundle bundleval = savedInstanceState.getBundle("bundle");
}
setTargetFragment()
• When a fragment returns some data back to the calling fragment, the calling
fragment should be set to communicate the data back.
• This is done with setTargetFragment() method. It takes two parameter- the Calling
Fragment instance and the request code (an integer number).

public void click(){


Fragment calledFragment =
F2.instantiate(getActivity().getApplicationContext(),"F2");
calledFragment.setTargetFragment(F1.this,101);
}
• When the Target is set, it automatically invoke the onActivityResult() of the Calling
fragment with the same request code.
Types of Fragments
• DialogFragment
Displays a floating dialog window over the activity

• ListFragment
displays and manages a list of items

• PreferenceFragment
displays preference objects
Dialog
• A dialog is a small window that prompts the user to make a decision or
enter additional information.
• The Dialog class is the base class for dialogs and are not instantiated
directly. Instead, use one of the following subclasses:

• AlertDialog
A dialog that can show a title, up to three buttons, a list of selectable items,
or a custom layout.
• DatePickerDialog or TimePickerDialog
A dialog with a pre-defined UI that allows the user to select a date or time.
Alert Dialog
• Alert Dialog shows the Alert message and collect responses in the
form of yes or no.
• Alert Dialog displays the message to warn you and then proceed
according to the response.
• Android Alert Dialog is built with the use of three fields:
• Title,
• Message area,
• Action Button.
Creating a alert dialog
• Create the object of Builder class Using AlertDialog.Builder.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
• set the Title, message, icon etc .
• setTitle() method for displaying the Alert Dialog box Title
• setMessage() method for displaying the message
• setIcon() method is use to set the icon on Alert dialog box.
• Set the action buttons and their listeners
• builder.setPositiveButton("Yes", Listener);
• builder.setNegativeButton("No", Listener);
• builder.setNeutralButton("Maybe", Listener);
• Create the dialog using the above builder and display it
AlertDialog dialog = builder.create();
dialog.show();
Note:
• To display other views on an alert dialog
builder.setView(inflater.inflate(R.layout.alert,null));
• To display a list
• String s[] ={“Mango”,”Grape”,”Banana”}; boolean ch={true, false,
false}
builder.setItems(s,Listener) // s is the array of items
builder.setSingleChoiceItems( s,0,Listener)
builder.setMultiChoiceItems(s,ch,listener)
• Toast / alert
Time limit automatically dispose
Action button
Views

Taost
Toast v/s Alert
• A toast provides simple feedback about an operation in a small popup.
It only fills the amount of space required for the message and the
current activity remains visible and interactive. Toasts automatically
disappear after a timeout.

• Alert dialogs should be used whenever an explicit response is needed


from the user, and that response is needed before anything else can
happen. Alert can be other views on it and can collect responses.
DialogFragment
• Dialog Fragment is a fragment that is used to make Dialogs that floats on
some Activity
• DialogFragment is a class which extends the Fragment class.
• DialogFragment introduced API level 11.

• public class myDialogFragment extends DialogFragment {


• @Override
• public Dialog onCreateDialog(Bundle savedInstanceState) {
• // use builder class to create dialogs.
• }
•}
DatePickerDialog and TimePickerDialog
• DatePickerDialog dpd = new
DatePickerDialog(Context,Listener,year,month, day);
• TimePickerDialog tpd = new
TimePickerDialog(Context,Listener,hour,minute,24HRformat);
• Dpd.show(); tpd.show()
• Listener:
DatePickerDialog.OnDateSetListener,
TimePickerDialog.OnTimeSetListener
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth)
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
Action Bar
• Android ActionBar is a consistent space that runs across the top of the
activity screen in android.
• Android ActionBar was launched by Google in 2013 with the release
of Android 3.0(API 11). Before that, the name of this top most visual
element was AppBar. AppBar contains only the name of the
application or current activity.
• The toolbar has been introduced in Android 5.0 (API 21).
• Android ActionBar can contain menu items which become visible
when the user clicks the “menu” button.
• makes the app consistent with other Android apps, allowing users to
quickly understand how to operate your app and have a great
experience.
Parts of Action Bar
• App Icon: App branding logo or icon will be displayed here
• View Control: A dedicated space to display Application title.
Also provides option to switch between views by adding
spinner or tabbed navigation
• Action Buttons: Some important actions of the app can be
added here
• Action Overflow: All unimportant action will be shown as a
menu
• Split Action Bar
• For devices with small screen, action bar will be
split into multiple bars. In such cases action bar will
have three bars to include its contents namely
• Main action bar: displays app icon, app title and
navigation button
• Top bar: displays tabs and drop downs
• Bottom bar: displays action buttons and overflow
actions.
Types

• Standard Action Bar,


• List Action Bar,
• Tabbed Action Bar
Standard Action Bar
• Create the resource directory Menu inside res folder
• Create XML menu resource file and define menu items in it.
• Get the action bar associated with the activity
ActionBar bar = this.getActionBar();
ActionBar bar = this.getSupportActionBar();
Use this method for AppCompatActivity.
• Set the action bar navigation mode to NAVIGATION_MODE_STANDARD
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
• Inflate the menu file to the activity inside onCreateOptionsMenu() method
• Override the method onOptionsItemSelected() to track the menu selection.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/done"
android:icon="@drawable/done"
android:title="Done"
app:showAsAction="always|withText"/>
<item
android:id="@+id/refresh"
android:icon="@drawable/refresh"
android:title="Refresh"
app:showAsAction="ifRoom"/>
• always to keep it in the ActionBar at all times
• ifRoom to keep it only if space is available
• never this means that the menu item will not be placed in the
ActionBar as an icon. It will only be visible when the menu button is
clicked, in the menu that’s popping up
• |withText : we can append this to either always or ifRoom, to indicate
that the toolbar button to be both the icon and the title, not just the
icon
Tabbed Action Bar
• Action Bar with tabs – used to logically organize contents.
• Action bar was introduced from API level 11.
• Tabbed action bar is created with fragments.
1.Get the action bar associated with the activity
ActionBar bar = getActionBar();
ActionBar bar = getSupportedActionBar();
2. Set the navigation mode to support tabs
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
3. Create as many tabs using newTab() method and add these tabs to the action bar
using addTab() method.
for(int i=1; i<= 3; i++) {
Tab tab = bar.newTab();
tab.setText("Tab "+ i);
tab.setTabListener(this);
bar.addTab(tab);
}
4.Implement TabListener interface and override its methods to track tab selection
changes.
5.Create fragments for each tab and display it when the appropriate tab is selected.
Logic to change tabs
public void onTabReselected (ActionBar.Tabtab,FragmentTransactionft){

Int tp = tab.getPosition();
if ( tp == 0){
F1 f = new F1();
ft.replace(android.R.id.content, f);
} else if (tp == 1) {
F2 f = new F2();
ft.replace(android.R.id.content, f);
}
}
List ActionBar
1. Get the action bar associated with the activity
ActionBar bar = this.getActionBar();
ActionBar bar = this.getSupportActionBar();
Use this method for AppCompatActivity.
2. Set the action bar navigation mode to support list as NAVIGATION_MODE_LIST
3. Prepare a list of items to be displayed in the drop down and create an adapter
class.
4. Attach the adapter to the action bar and associate the navigation listener to
track the item selection
5. Implement the onNavigationItemSelected() method to get the list selection
Custom views on action bar
1. Create a layout as
<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/searchfield"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="textFilter" >
</EditText>

2. Create an activity and add the layout to the action bar using setCustomView()
ActionBar actionBar=getActionBar();
actionBar.setCustomView(R.layout.cvl);
EditText search =
(EditText)actionBar.getCustomView().findViewById(R.id.searchfield);
search.setOnEditorActionListener(newOnEditorActionListener(){
@Override
public boolean onEditorAction(TextView v,int actionId,KeyEvent event){
Toast.makeText(MainActivity.this,"Search triggered",
Toast.LENGTH_LONG).show();
return false;
}
});
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM
|ActionBar.DISPLAY_SHOW_HOME);
Services
• A Service is an application component that can perform long-running
operations in the background.
• It does not provide a user interface.
• Once started, a service might continue running for some time, even
after the user switches to another application.
• A component can bind to a service to interact with it and even perform
inter-process communication (IPC).
• For example, a service can handle network transactions, play music,
perform file I/O, or interact with a content provider, all from the
background.
Types of Services
1. Foreground Services:
• A foreground service performs some operation that is noticeable to
the user.
• For example, an audio app would use a foreground service to play an
audio track.
• Foreground services must display a Notification so that users are
aware that the service is running.
• Foreground services continue running even when the user isn't
interacting with the app
2. Background
• A background service performs an operation that isn't directly noticed
by the user
• Eg: data synch
3. Bound Service:
• A service is bound when an application component binds to it by
calling bindService().
• A bound service runs only as long as another application component
is bound to it. Multiple components can bind to the service at once,
but when all of them unbind, the service is destroyed.
• A bound service offers a client-server interface that allows
components to interact with the service, send requests, receive
results
• Started Service (Unbounded Service):
• A service initiated by an application component using
the startService() method.
• Once initiated, the service can run continuously in the background even
if the component is destroyed which was responsible for the start of the
service.
Life Cycle
onCreate()
• Whenever a service is created either using onStartCommand() or
onBind(), the android system calls this method.
• This method is necessary to perform a one-time-set-up.

onStartCommand()
• The Android service calls this method when a component(eg: activity)
requests to start a service using startService().
• Once the service is started, it can be stopped explicitly using
stopService() or stopSelf() methods.
onBind()
• This method is mandatory to implement in android service and is
invoked whenever an application component calls the bindService()
method in order to bind itself with a service.
• User-interface is also provided to communicate with the service
effectively by returning an IBinder object.
• If the binding of service is not required then the method must return
null.
onUnbind()
• The Android system invokes this method when all the clients
• get disconnected from a particular service interface.

onRebind()
• Once all clients are disconnected from the particular interface of
service and there is a need to connect the service with new clients,
the system calls this method
onDestroy()
• When a service is no longer in use, the system invokes this
method just before the service destroys as a final clean up call.
• Services must implement this method in order to clean up resources
like registered listeners, threads, receivers, etc.
Creating a service
public class MyService extends Service {
public int onStartCommand(Intent intent, int flags, int startId) {}
public void onDestroy() {}
public IBinder onBind(Intent intent) {}
}

Manifest:
<application>
------
<service android:name=".MyService"/>
</application>
• startService(new Intent( this, MyService.class ) );
• stopService(new Intent( this, MyService.class ) );

You might also like