MY mENU


Monday 13 February 2012

Services in Android

Services :- A service is a component that runs in the background for an indefinite period of time, and which doesn’t provide a user interface. As with an activity, a service runs on the
process’s main thread; it must spawn another thread to perform a time-consuming operation. Services support true multitasking for Android, as they can run in their own processWe can start the another services and it will continue to run in the background even if the user switches to another application. It even perform inter process communication (IPC).

A service is not a separate process, although it can be specified to run in a separate process. Also, a service is not a thread. Instead, a service lets the app tell Android about something it wants to be doing in the background (even when the user is not directly interacting with the app), and lets the app expose some of its functionality to other apps.

This service is used handle network transactions, play music, perform file I/O, or interact with a content provider, all running in the background.


started and bundle are two form of service.

1.Started :- The service start when We called the start service method by the activity. when another component calls startService() then services is start. Once service started,  a service can run in the background indefinitely and must stop itself by calling stopSelf(), even if the component that started it is destroyed. 

For example, download or upload a file over the network. When the operation is done, the service should stop itself.

2.Bound :- This method is used to bound the service when an application component binds to it by calling bindService(). This service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with inter-process communication (IPC).The client can close the connection by calling unbindService(). Multiple clients can bind to the same service and when all of them unbind, the system destroys the service. 


Service needs to be declared in the AndroidManifest.xml via a service android:name="yourclasss" and the implementing class must extend the class Service or one of its sub-classes.
You can also specify that your Service should run in a different process then your application via the android:process=":process_description" attribute. This way the service gets its own process and has its own memory. Therefore any low running operation in the Service, e.g. a garbage collection, will not affect the user interface.

Service will not automatically run in its own thread. Without the process attribute they run the main thread of their hosting process. Therefore you should run performance intensive tasks in the background.

Life Cycle of Service : Life cycle of service is same as Activity life cycle. Service has many life-cycle callback methods. There are some life cycle method :

1.startService() :-This method is called when application service be started.This method return  the ComponentName of the actual service.  

public abstract ComponentName startService (Intent service)

2. onCreate() :- This method is called  by the system when the service is first created. Do not call this method directly.
              
                                public void onCreate ()

3.onStartCommand() :- This method is called by the system every time a client explicitly starts the service by calling startService(Intent), providing the arguments it supplied and a unique integer token representing the start request. 
       
                          public int onStartCommand (Intent intent, int flags, int startId)

4.onBind() :- This method is return the communication channel to the service. 
This method return null  if clients can not bind to the service otherwise return  IBinder

                           public abstract IBinder onBind (Intent intent)

5.onUnbind() :- This method is called when all clients have disconnected from a particular interface published by the service.This method return boolean value.The default implementation does nothing and returns false.

                            public boolean onUnbind (Intent intent)

6.onRebind() :-   This method is called when new clients have connected to the service, after it had previously been notified that all had disconnected in its onUnbind(Intent).
                             public void onRebind (Intent intent)

7.onDestroy() :-This method is called by the system to notify a Service that it is no longer used and is being removed

                            public void onDestroy ()

Services are classified as local or remote.
  • A local service runs in the same process as the rest of the app. Such services make it easy to implement background tasks.
  • A remote service runs in a separate process. Such services let you perform interprocess communications.

AlertDialog in Android


A "Toast" which is a quick small message window which does not take the focus.  (Java.lang.object)
 AlertDialog is used to open a dialog from our activity. This modal dialog gets the focus until the user closes it.
An instance of this class can be created by the builder pattern, e.g. you can chain your method calls.
You should always open a dialog from the class onCreateDialog(int) as the Android system manages the dialog in this case for you. This method is automatically called by Android if you call showDialog(int).
Syntax:

                         AlertDialog showAlert=new AlertDialog.Builder(this).create();
showAlert.setTitle("it's clicked");
showAlert.setMessage("are you sure you want to Burn?");
showAlert.setButton("Burn",new OnClickListener(){
                               @Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel(); }
                                                                         });
                                                    showAlert.show();



Emulator,Logcat and AVD in Android


The Android Development Tools (ADT) include an emulator to run an Android system. The emulator behaves like a real Android device (in most cases) and allows you to test your application without having a real device.
You can configure the version of the Android system you would like to run, the size of the SD card, the screen resolution and other relevant settings. You can define several devices with different configurations.
Via the emulator you select which device should be started, you can also start several in parallel. These devices are called "Android Virtual Device" (AVD).
The ADT allow to deploy and run your Android program on the AVD.

During the creation of an AVD you decide if you want an Android device or an Google device.
An AVD created for Android will contain the programs from the Android Open Source Project. An AVD created for the Google API's will also contain several Google applications, most notable the Google Maps application.
If you want to use functionality which is only provided via the Google API's, e.g. Cloud2DeviceMessaging or Google Maps you must run this application on an AVD with Google API's.
(Shortcuts for Emulator
Alt+Enter Maximizes the emulator. Ctrl+F11 changes the orientation of the emulator. F8 Turns network on / off.)

Logcat:
The "LogCat" View shows you the log messages of your Android device and help you analyze problems. For example Java exceptions in your program would be shown here. To open this view, select Window → Show View →Other → Android → LogCat.

Avoid Restart Activity in Android


You can avoid a restart of your application for certain configuration changes via the configChanges attribute on your activity definition in your AndroidManifest.xml. The following activity will not be restarted in case of orientation changes or position of the physical keyboard (hidden / visible).

    
<activity android:name=".ProgressTestActivity"
     android:label="@string/app_name"
     android:configChanges="orientation|keyboardHidden|keyboard">
</activity>

Activity and it's Lifecycle

An Activity is an application component that provides a screen with which users can interact in order to do something, such as dial the phone, take a photo, send an email, or view a map. An activity presents a visual user interface for one focused endeavor the user can undertake. Typically, one activity in an application is specified as the "main" activity, which is presented to the user when launching the application for the first time. 


When an activity is stopped because a new activity starts, it is notified of this change in state through the activity's life-cycle callback methods. There are several callback methods that an activity might receive, due to a change in its stateThese state transitions are all part of the activity life-cycle.
1. onCreate();  must implemented method. The system calls this when creating your activity. Within your implementation, you should initialize the essential components of your activity. Most importantly, this is where you must call setContentView() to define the layout for the activity's user interface.
2. onStart(); Called just before the activity becomes visible to the user.
3. onResume(); The activity is in the foreground of the screen and has user focus. (This state is also sometimes referred to as "running".)

4. onPause(); calls this method as the first indication that the user is leaving your activity (not destroyed). This is usually where you should commit any changes that should be persisted beyond the current user session (because the user might not come back).

5. onStop(); Called when the activity is no longer visible to the user, may happen because it is being destroyed.

6. onDestroy(); Called before the activity is destroyed. It could be called while the activity is finishing.

onSaveInstanceState() - called if the activity is stopped. Used to save data of that activity so that the activity can restore its states if it re-started.
public class ExAct extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // The activity is being created.
    }
    @Override
    protected void onStart() {
        super.onStart();
        // The activity is about to become visible.
    }
    @Override
    protected void onResume() {
        super.onResume();
        // The activity has become visible (it is now "resumed").
    }
    @Override
    protected void onPause() {
        super.onPause();
        // Another activity is taking focus (this activity is about to be "paused").
    }
    @Override
    protected void onStop() {
        super.onStop();
        // The activity is no longer visible (it is now "stopped")
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // The activity is about to be destroyed.
    }
}

through implementing these life cycle we described as below
Entire Lifetime of an Activity comes between onCreate() to onDestroy().
Visible Lifetime of an Activity comes between onStart() to onStop().
Foreground Lifetime of an Activity comes between onResume() to onPause().