Unit 4
Unit 4
@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).
• 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.
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 ) );