Develop series-API Guides-application components-Services,-api-services

Source: Internet
Author: User

Develop series-API Guides-application components-Services,-api-services
Services

Services: It can be run on the backend for a long time without a UI.

Started:

   

Services is started by calling startService through other components, and can run continuously in the background even if its components have been destroyed. Generally, this type of service performs a specific operation without returning values. For example, if a file is downloaded or uploaded over the network, the Service must stop itself once the operation is completed.

Bound:

   

The Service uses other components to call bindService binding. It provides an CS architecture interface that allows other components to interact with the Service, send messages, obtain returned values, and even communicate with each other across processes. The bound service and the components bound to it coexist. Multiple components can be bound to a service. When all the components bound to the service are unbound, the service will be destroyed.

Caution: the Service runs in the main thread of the host process. That is to say, the Service does not create its own thread or run in another process (unless specified ). This means that if the Service executes some tasks with high CPU load or blocking interface operations, you need to create a new thread to run it to reduce the ANR risk.

(Using service or thread? If you only need to execute additional tasks outside the main thread when interacting with users, you need to create a new thread instead of a Service. For example, to play music when the activity is displayed on the foreground, you need to create a thread in onCreate, run the onStart thread, and stop the thread in onStop, of course, you can also use AsyncTask or HandleThread to replace the Thread class .)

Basic

Create a subclass of the Service and overwrite the key callback functions in the Service life cycle. If necessary, provide a Service binding mechanism. The most important callback functions are as follows:

OnStartCommand

   

When other components call startService to start the Service, the Service is always executed in the background. If you implement this method, you have the responsibility to stop the Service by stopSelf or stopService when the Service completes its work. (This method is not required if only Service binding is provided)

OnBind

   

The system is executed when other components call bindService to bind a Service. In the implementation of this method, you need to return an IBider interface for clients to interact with the service. If you do not need to bind, you can directly return null

OnCreate

   

The Service is executed when it is created for the first time. Before onStartCommand and onBind, it is used to execute data that needs to be initialized once.

OnDestroy

   

It is executed when the service is destroyed and used to clear resources, such as threads, registration listeners, and referers.

 

The system forcibly stops the service when the memory is low. If a service is bound to an activity with a user focus, it is rarely destroyed. If a service is defined as running on the foreground, it will never be destroyed.

Define service in manifest
<manifest ... >  ...  <application ... >      <service android:name=".ExampleService" />      ...  </application></manifest>

Android: name is a unique property that is required. Other attributes can be selected. Once your application is released, you should never change the android: name.

To ensure security, use an explicit Intent to start or bind the service, instead of defining filiters. If multiple services are allowed to respond, you must use setPackage in Intent to specify the registration to reduce the probability of unexpected value matching for the target service.

Set android: exported to false to prevent other applications from starting this service.

Create a service

Service

  

The base classes of all services. If you expand this class, you may need to create a new thread. Because this service room is executed in the main thread of the app, it may reduce the smoothness of the activity.

IntentService

  

Service subclass, which processes all requests through a working thread, one at a time. If your service does not need to process multiple requests at the same time, IntentService is the best choice.

Extended IntentService

Because most services do not need to process multiple requests at the same time (in fact, it is a multi-threaded scenario), IntentService is the best recommendation.

The IntentService workflow is as follows:

  • Create a default new worker thread to execute all intents distributed to onStartCommand.
  • Create a work queue to pass intent in sequence to execute the onHandleIntent specific implementation, so you do not need to consider the multi-thread scenario
  • All requests are automatically destroyed after execution. You do not need to execute stopSelf.
  • Provides the default onBind implementation: returns null directly.
  • OnStartCommand default implementation is provided: intent is sent to the worker thread for onHandleIntent implementation.

In fact, you need to implement onHandleIntent, as shown in the following example:

  public class HelloIntentService extends IntentService {  /**   * A constructor is required, and must call the super IntentService(String)   * constructor with a name for the worker thread.   */  public HelloIntentService() {      super("HelloIntentService");  }  /**   * The IntentService calls this method from the default worker thread with   * the intent that started the service. When this method returns, IntentService   * stops the service, as appropriate.   */  @Override  protected void onHandleIntent(Intent intent) {      // Normally we would do some work here, like download a file.      // For our sample, we just sleep for 5 seconds.      long endTime = System.currentTimeMillis() + 5*1000;      while (System.currentTimeMillis() < endTime) {          synchronized (this) {              try {                  wait(endTime - System.currentTimeMillis());              } catch (Exception e) {              }          }      }  }}

If you need to override other callbacks, such as onCreate, onStartCommand, and onDestroy, make sure to call the implementation of the parent class so that IntentService can process the life cycle of the worker thread. OnHandleIntent and onBind are exceptions.

Extended Service

If the Service needs to support multithreading (rather than one-to-one processing through the work queue), you need to extend the Service to process each intent.

For comparison, the following code has the same functions as the above Code.

public class HelloService extends Service {  private Looper mServiceLooper;  private ServiceHandler mServiceHandler;  // Handler that receives messages from the thread  private final class ServiceHandler extends Handler {      public ServiceHandler(Looper looper) {          super(looper);      }      @Override      public void handleMessage(Message msg) {          // Normally we would do some work here, like download a file.          // For our sample, we just sleep for 5 seconds.          long endTime = System.currentTimeMillis() + 5*1000;          while (System.currentTimeMillis() < endTime) {              synchronized (this) {                  try {                      wait(endTime - System.currentTimeMillis());                  } catch (Exception e) {                  }              }          }          // Stop the service using the startId, so that we don't stop          // the service in the middle of handling another job          stopSelf(msg.arg1);      }  }  @Override  public void onCreate() {    // Start up the thread running the service.  Note that we create a    // separate thread because the service normally runs in the process's    // main thread, which we don't want to block.  We also make it    // background priority so CPU-intensive work will not disrupt our UI.    HandlerThread thread = new HandlerThread("ServiceStartArguments",            Process.THREAD_PRIORITY_BACKGROUND);    thread.start();    // Get the HandlerThread's Looper and use it for our Handler    mServiceLooper = thread.getLooper();    mServiceHandler = new ServiceHandler(mServiceLooper);  }  @Override  public int onStartCommand(Intent intent, int flags, int startId) {      Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();      // For each start request, send a message to start a job and deliver the      // start ID so we know which request we're stopping when we finish the job      Message msg = mServiceHandler.obtainMessage();      msg.arg1 = startId;      mServiceHandler.sendMessage(msg);      // If we get killed, after returning from here, restart      return START_STICKY;  }  @Override  public IBinder onBind(Intent intent) {      // We don't provide binding, so return null      return null;  }  @Override  public void onDestroy() {    Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();  }}

This only simulates IntentService processing. If necessary, you can create a thread for each request.

 

OnStartCommand must return an integer to describe how the system processes this service when it is destroyed by an exception.

START_NOT_STICKY

  

If the service is destroyed abnormally after the onStartCommand is executed, you do not need to re-create the service unless there are still unprocessed intents. To avoid unnecessary Service Startup, your application can easily restart unfinished work and select this option.

START_STICKY

  

If the service is destroyed abnormally after onStartCommand is executed, re-create the service and execute onStartCommand. However, the last intent sent to the service is not used, but onStartCommand is executed through a null intent, unless there are still unprocessed intents. In this case, it is suitable for running in the background or waiting for media playback of the task without executing the command.

START_REDELIVER_INTENT

  

If the service is destroyed abnormally after the onStartCommand is executed, re-create the service and use the last intent sent to the service to call onStartCommand. Other unprocessed intents are distributed in sequence. This situation is suitable for scenarios where the tasks to be executed need to understand recovery, such as downloading files.

Start the service

StartService-> onStartCommand

Intent intent = new Intent(this, HelloService.class);startService(intent);

The startService method returns immediately.

If the service cannot be bound, it can only be started through startService. When you need to send a return value, you can create a PendingIntent (getBroadcast) with delayed broadcast to start the service, the service can use the broadcast in it to distribute the results.

Stop Service

If the service processes multiple requests synchronously, one request cannot be directly destroyed after processing. Other requests may have just been sent or are still being processed. To avoid this situation, you can use stopSelf (int) to ensure that the service to be closed is the service that has just processed the request, rather than other services that are being processed. The integer parameter uniquely identifies the service instance.

Create a binding Service

For details, see the next chapter.

Send Notifications to users

Once the service is running, you can use Toast Notifications and Status Bar Notifications to remind users.

Run the service on the front-end

The Service Running on the foreground must provide a status bar notification to display the running status. The notification will not disappear unless the service is stopped or removed.

For example, when playing a music, a notification is provided in the status bar to tell the user the current song to be played, providing the user's entry to the music player.

The service needs to run in the foreground and call startForground. The first parameter is the unique identifier of notification (not 0). The first parameter is notification, for example:

Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),        System.currentTimeMillis());Intent notificationIntent = new Intent(this, ExampleActivity.class);PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);notification.setLatestEventInfo(this, getText(R.string.notification_title),        getText(R.string.notification_message), pendingIntent);startForeground(ONGOING_NOTIFICATION_ID, notification);

Stop running on the foreground. You can call stopForeground.

Implement lifecycle callback
public class ExampleService extends Service {    int mStartMode;       // indicates how to behave if the service is killed    IBinder mBinder;      // interface for clients that bind    boolean mAllowRebind; // indicates whether onRebind should be used    @Override    public void onCreate() {        // The service is being created    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        // The service is starting, due to a call to startService()        return mStartMode;    }    @Override    public IBinder onBind(Intent intent) {        // A client is binding to the service with bindService()        return mBinder;    }    @Override    public boolean onUnbind(Intent intent) {        // All clients have unbound with unbindService()        return mAllowRebind;    }    @Override    public void onRebind(Intent intent) {        // A client is binding to the service with bindService(),        // after onUnbind() has already been called    }    @Override    public void onDestroy() {        // The service is no longer used and is being destroyed    }}

Note: The implementation of the parent class is not required.

 

Complete lifecycle: onCreate-> onDestroy

Activity lifecycle: onStartCommand/onBind-> onDestroy/onUnbind




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.