Wednesday, 15 March 2017

Android Services

A Service is an application component that can perform long-running operations in the background, and it does not provide a user interface. Another application component can start a service, and it continues to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess 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.

 These are the three different types of services:

1. Scheduled
 
A service is scheduled when an API such as the JobScheduler, introduced in Android 5.0 (API level 21), launches the service. You can use the JobScheduler by registering jobs and specifying their requirements for network and timing. The system then gracefully schedules the jobs for execution at the appropriate times. The JobScheduler provides many methods to define service-execution conditions.
2. Started
A service is started when an application component (such as an activity) calls startService(). After it's started, a service can run in the background indefinitely, even if the component that started it is destroyed. Usually, a started service performs a single operation and does not return a result to the caller. For example, it can download or upload a file over the network. When the operation is complete, the service should stop itself.
3. Bound
 
A service is bound when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, receive results, and even do so across processes with interprocess communication (IPC). 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 service has life cycle callback methods that you can implement to monitor changes in the service's state and you can perform work at the appropriate stage. The following diagram on the left shows the life cycle when the service is created with startService() and the above diagram shows the life cycle when the service is created with bindService().
To create a service, you must create a subclass of Service or use one of its existing subclasses. In your implementation, you must override some callback methods that handle key aspects of the service lifecycle and provide a mechanism that allows the components to bind to the service, if appropriate. These are the most important callback methods that you should override:
  
1. onStartCommand() 

The system invokes this method by calling startService() when another component (such as an activity) requests that the service be started. When this method executes, the service is started and can run in the background indefinitely. If you implement this, it is your responsibility to stop the service when its work is complete by calling stopSelf() or stopService(). If you only want to provide binding, you don't need to implement this method.
 2. onBind()
 
The system invokes this method by calling bindService() when another component wants to bind with the service (such as to perform RPC). In your implementation of this method, you must provide an interface that clients use to communicate with the service by returning an IBinder. You must always implement this method; however, if you don't want to allow binding, you should return null.
  
3. onCreate()
The system invokes this method to perform one-time setup procedures when the service is initially created (before it calls either onStartCommand() or onBind()). If the service is already running, this method is not called. 
4. onDestroy()
The system invokes this method when the service is no longer used and is being destroyed. Your service should implement this to clean up any resources such as threads, registered listeners, or receivers. This is the last call that the service receives.
Below is an example of program to create a service class -
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;


public class MyService extends Service {
   @Nullable
   @Override
   public IBinder onBind(Intent intent) {
      return null;
   }
 
   @Override
   public int onStartCommand(Intent intent, int flags, 
                              int startId) {
      // Let it continue running until it is stopped.
      Toast.makeText(this, "Service Started", 
                      Toast.LENGTH_LONG).show();
      return START_STICKY;
   }

   @Override
   public void onDestroy() {
      super.onDestroy();
      Toast.makeText(this, "Service Destroyed", 
                      Toast.LENGTH_LONG).show();
   }
}
 To run the service you can create two buttons in your program xml file and create two methods to start and stop the service.Method examples are shown below-

 public void startService(View view) {
      startService(new Intent(getBaseContext(), 
                    MyService.class));
   }

   // Method to stop the service
   public void stopService(View view) {
      stopService(new Intent(getBaseContext(),
                   MyService.class));
   }

After creating service class you need to declare the service in the android manifest file also -

<manifest ... >
  ...
  <application ... >
      <service android:name=".nameofservice" />
      ...
  </application>
</manifest>

No comments:

Post a Comment