Offical explanation of service in 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, allfrom the background.

These are the three different types of services:

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.

Note: If your app targets Android 5.0 (API level 21), Google recommends that you use theJobScheduler to execute background services. For more information about using this class, see theJobScheduler reference documentation.

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.
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.

Although this documentation generally discusses started and bound services separately,your service can work both ways—it can be started (to run indefinitely) and also allow binding. It's simply a matter of whether you implement a couple of callback methods: onStartCommand() to allow components to start it and onBind() to allow binding.

Regardless of whether your application is started, bound, or both, any application componentcan use the service (even from a separate application) in the same way that any component can usean activity—by starting it with an Intent. However, you can declarethe service asprivate in the manifest file and block access from other applications.This is discussed more in the section about Declaring the service in themanifest.

Caution: A service runs in the main thread of its hosting process; the service does not create its own thread and does not run in a separate process unless you specify otherwise. If your service is going to perform any CPU-intensive work or blocking operations, such as MP3playback or networking, you should create a new thread within the service to complete that work.By using a separate thread, you can reduce the risk of Application Not Responding (ANR) errors,and the application's main thread can remain dedicated to user interaction with your activities.

The basics


To create a service, you must create a subclass of Service or use oneof 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:

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.
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.
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.
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.

If a component starts the service by calling startService() (which results in a call to onStartCommand()), the service continues to run until it stops itself withstopSelf() or anothercomponent stops it by calling stopService().

If a component calls bindService() to create the service and onStartCommand() isnot called, the service run sonly as long as the component is bound to it. After the service is unbound from all of its clients,the system destroys it.

The Android system force-stops a service only when memory is low and it must recover system resources for the activity that has user focus. If the service is bound to an activity that has user focus, it's less likely to be killed; if the service is declared to run in the foreground, it's rarely killed.If the service is started and is long-running, the system lowers its positionin the list of background tasks over time, and the service becomes highly susceptible tokilling—if your service is started, you must design it to gracefully handle restartsby the system. If the system kills your service, it restarts it as soon as resources becomeavailable, but this also depends on the value that you return fromonStartCommand(). For more informationabout when the system might destroy a service, see theProcesses and Threadingdocument.

In the following sections, you'll see how you can create thestartService() andbindService() service methods, as well as how to usethem from other application components.

Declaring a service in the manifest

You must declare all services in your application'smanifest file, just as you do for activities and other components.

To declare your service, add a <service> elementas a child of the <application>element. Here is an example:

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

See the <service> elementreference for more information about declaring your service in the manifest.

There are other attributes that you can include in the <service> element todefine properties such as the permissions that are required to start the service and the process inwhich the service should run. Theandroid:nameattribute is the only required attribute—it specifies the class name of the service. Afteryou publish your application, leave this name unchanged to avoid the risk of breakingcode due to dependence on explicit intents to start or bind the service (read the blog post, ThingsThat Cannot Change).

Caution: To ensure that your app is secure, always use anexplicit intent when starting aService and do not declare intent filters foryour services. Using an implicit intent to start a service is a security hazard because you cannotbe certain of the service that will respond to the intent, and the user cannot see which servicestarts. Beginning with Android 5.0 (API level 21), the system throws an exception if you callbindService() with an implicit intent.

You can ensure that your service is available to only your app byincluding theandroid:exportedattribute and setting it to false. This effectively stops other apps from starting yourservice, even when using an explicit intent.

Note: Users can see what services are running on their device. If they see a service that they don't recognize or trust, they can stop the service. In order to avoid having your service stopped accidentally by users, you need to add the android:description attribute to the <service> element in your app manifest. In the description, provide a short sentence explaining what the service does and what benefits it provides.

Creating a started service


A started service is one that another component starts by calling startService(), which results in a call to the service'sonStartCommand() method.

When a service is started, it has a lifecycle that's independent of thecomponent that started it. The service can run in the background indefinitely, even ifthe component that started it is destroyed. As such, the service should stop itself when its jobis complete by calling stopSelf(), or another component canstop it by callingstopService().

An application component such as an activity can start the service by calling startService() and passing anIntentthat specifies the service and includes any data for the service to use. The service receivesthisIntent in theonStartCommand() method.

For instance, suppose an activity needs to save some data to an online database. The activitycan start a companion service and deliver it the data to save by passing an intent tostartService(). The service receives the intent inonStartCommand(), connects to the Internet, and performs thedatabase transaction. When the transaction is complete, the service stops itself and isdestroyed.

Caution: A service runs in the same process as the applicationin which it is declared and in the main thread of that application by default. If your serviceperforms intensive or blocking operations while the user interacts with an activity from the sameapplication, the service slows down activity performance. To avoid impacting applicationperformance, start a new thread inside the service.

Traditionally, there are two classes you can extend to create a started service:

Service
This is the base class for all services. When you extend this class, it's important tocreate a new thread in which the service can complete all of its work; the service uses yourapplication's main thread by default, which can slow the performance of any activity that yourapplication is running.
IntentService
This is a subclass of Service that uses a worker thread to handle all ofthe start requests, one at a time. This is the best option if you don't require that your servicehandle multiple requests simultaneously. Implement onHandleIntent(), which receives the intent for eachstart request so that you can complete the background work.

The following sections describe how you can implement your service using either one for theseclasses.

Extending the IntentService class

Because most of the started services don't need to handle multiple requests simultaneously(which can actually be a dangerous multi-threading scenario), it's best that youimplement your service using theIntentService class.

The IntentService class does the following:

  • It creates a default worker thread that executes all of the intents that are delivered toonStartCommand(), separate from your application's mainthread.
  • Creates a work queue that passes one intent at a time to your onHandleIntent() implementation, so you never have toworry about multi-threading.
  • Stops the service after all of the start requests are handled, so you never have to callstopSelf().
  • Provides a default implementation of onBind() that returns null.
  • Provides a default implementation of onStartCommand() that sends the intent to the work queue and then to your onHandleIntent() implementation.

To complete the work that is provided by the client, implement onHandleIntent().However, you also need to provide a small constructor for the service.

Here's an example implementation of IntentService:

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.
      try {
          Thread.sleep(5000);
      } catch (InterruptedException e) {
          // Restore interrupt status.
          Thread.currentThread().interrupt();
      }
  }
}

That's all you need: a constructor and an implementation of onHandleIntent().

If you decide to also override other callback methods, such as onCreate(),onStartCommand(), oronDestroy(), be sure to call the super implementation sothat theIntentService can properly handle the life of the worker thread.

For example, onStartCommand() must returnthe default implementation, which is how the intent is delivered to onHandleIntent():

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
    return super.onStartCommand(intent,flags,startId);
}

Besides onHandleIntent(), the only methodfrom which you don't need to call the super class isonBind(). You need to implement this only if your service allows binding.

In the next section, you'll see how the same kind of service is implemented when extendingthe baseService class, which uses more code, but might beappropriate if you need to handle simultaneous start requests.

Extending the Service class

Using IntentService makes yourimplementation of a started service very simple. If, however, you require your service toperform multi-threading (instead of processing start requests through a work queue), youcan extend the Service class to handle each intent.

For comparison, the following example code shows an implementation of the Service class that performs the same work as the previous example usingIntentService. That is, for each start request, it uses a worker thread to perform thejob and processes only one request at a time.

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.
          try {
              Thread.sleep(5000);
          } catch (InterruptedException e) {
              // Restore interrupt status.
              Thread.currentThread().interrupt();
          }
          // 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();
  }
}

As you can see, it's a lot more work than using IntentService.

However, because you handle each call to onStartCommand() yourself, you can perform multiple requests simultaneously. That's not whatthis example does, but if that's what you want, you can create a new thread for eachrequest and run them right away instead of waiting for the previous request to finish.

Notice that the onStartCommand() method must return aninteger. The integer is a value that describes how the system should continue the service in theevent that the system kills it. The default implementation forIntentService handles this for you, but you are able to modify it. The return valuefromonStartCommand() must be one of the followingconstants:

START_NOT_STICKY
If the system kills the service after onStartCommand() returns, do not recreate the service unless there are pendingintents to deliver. This is the safest option to avoid running your service when not necessaryand when your application can simply restart any unfinished jobs.
START_STICKY
If the system kills the service after onStartCommand() returns, recreate the service and call onStartCommand(), but do not redeliver the last intent.Instead, the system calls onStartCommand() with anull intent unless there are pending intents to start the service. In that case,those intents are delivered. This is suitable for media players (or similar services) that are notexecuting commands but are running indefinitely and waiting for a job.
START_REDELIVER_INTENT
If the system kills the service after onStartCommand() returns, recreate the service and call onStartCommand() with the last intent that was delivered to theservice. Any pending intents are delivered in turn. This is suitable for services that areactively performing a job that should be immediately resumed, such as downloading a file.

For more details about these return values, see the linked reference documentation for eachconstant.

Starting a service

You can start a service from an activity or other application component by passing anIntent (specifying the service to start) tostartService(). The Android system calls the service'sonStartCommand() method and passes it theIntent.

Note: Never callonStartCommand() directly.

For example, an activity can start the example service in the previous section (HelloService) using an explicit intent withstartService(), as shown here:

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

The startService() method returns immediately, andthe Android system calls the service'sonStartCommand() method. If the service is not already running, the system first callsonCreate(), and then it callsonStartCommand().

If the service does not also provide binding, the intent that is delivered withstartService() is the only mode of communication between theapplication component and the service. However, if you want the service to send a result back,the client that starts the service can create aPendingIntent for a broadcast(withgetBroadcast()) and deliver it to the servicein theIntent that starts the service. The service can then use thebroadcast to deliver a result.

Multiple requests to start the service result in multiple corresponding calls to the service'sonStartCommand(). However, only one request to stopthe service (with stopSelf() orstopService()) is required to stop it.

Stopping a service

A started service must manage its own lifecycle. That is, the system does not stop ordestroy the service unless it must recover system memory and the servicecontinues to run afteronStartCommand() returns. Theservice must stop itself by callingstopSelf(), or anothercomponent can stop it by callingstopService().

Once requested to stop with stopSelf() orstopService(), the system destroys the service as soon aspossible.

If your service handles multiple requests to onStartCommand() concurrently, you shouldn't stop theservice when you're done processing a start request, as you might have received a newstart request (stopping at the end of the first request would terminate the second one). To avoidthis problem, you can usestopSelf(int) to ensure that your request tostop the service is always based on the most recent start request. That is, when you callstopSelf(int), you pass the ID of the start request (thestartIddelivered to onStartCommand()) to which your stop requestcorresponds. Then, if the service receives a new start request before you are able to call stopSelf(int), the ID does not match and the service does not stop.

Caution: To avoid wasting system resources and consumingbattery power, ensure that your application stops its services when it's done working.If necessary, other components can stop the service by callingstopService(). Even if you enable binding for the service,you must always stop the service yourself if it ever receives a call to onStartCommand().

For more information about the lifecycle of a service, see the section below aboutManaging the Lifecycle of a Service.

Creating a bound service


A bound service is one that allows application components to bind to it by callingbindService() to create a long-standing connection.It generally doesn't allow components to start it by calling startService().

Create a bound service when you want to interact with the service from activitiesand other components in your application or to expose some of your application's functionality toother applications through interprocess communication (IPC).

To create a bound service, implement the onBind() callback method to return anIBinder thatdefines the interface for communication with the service. Other application components can then callbindService() to retrieve the interface andbegin calling methods on the service. The service lives only to serve the application component thatis bound to it, so when there are no components bound to the service, the system destroys it.You donot need to stop a bound service in the same way that you must when the service isstarted throughonStartCommand().

To create a bound service, you must define the interface that specifies how a client cancommunicate with the service. This interface between the serviceand a client must be an implementation ofIBinder and is what your service mustreturn from theonBind() callback method. After the client receives theIBinder, it can begininteracting with the service through that interface.

Multiple clients can bind to the service simultaneously. When a client is done interacting withthe service, it callsunbindService() to unbind.When there are no clients bound to the service, the system destroys the service.

There are multiple ways to implement a bound service, and the implementation is morecomplicated than a started service. For these reasons, the bound service discussion appears in aseparate document aboutBound Services.

Sending notifications to the user


When a service is running, it can notify the user of events using Toast Notifications or Status Bar Notifications.

A toast notification is a message that appears on the surface of the current window for only amoment before disappearing. A status bar notification provides an icon in the status bar with amessage, which the user can select in order to take an action (such as start an activity).

Usually, a status bar notification is the best technique to use when background work such asa file download has completed, and the user can now act on it. When the userselects the notification from the expanded view, the notification can start an activity(such as to display the downloaded file).

See the Toast Notifications or Status Bar Notificationsdeveloper guides for more information.

Running a service in the foreground


A foreground service is a service that theuser is actively aware of and is not a candidate for the system to kill when low on memory. Aforeground service must provide a notification for the status bar, which is placed under theOngoing heading. This means that the notification cannot be dismissed unless the serviceis either stopped or removed from the foreground.

For example, a music player that plays music from a service should be set to run in theforeground, because the user is explicitly awareof its operation. The notification in the status bar might indicate the current song and allowthe user to launch an activity to interact with the music player.

To request that your service run in the foreground, call startForeground(). This method takes two parameters: aninteger that uniquely identifies the notification and the Notification for the status bar. Here is an example:

Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

Notification notification = new Notification.Builder(this)
    .setContentTitle(getText(R.string.notification_title))
    .setContentText(getText(R.string.notification_message))
    .setSmallIcon(R.drawable.icon)
    .setContentIntent(pendingIntent)
    .setTicker(getText(R.string.ticker_text))
    .build();

startForeground(ONGOING_NOTIFICATION_ID, notification);

Caution: The integer ID that you give to startForeground() must not be 0.

To remove the service from the foreground, call stopForeground(). This method takes a boolean, which indicateswhether to remove the status bar notification as well. This method does not stop theservice. However, if you stop the service while it's still running in the foreground, thenotification is also removed.

For more information about notifications, see Creating Status BarNotifications.

Managing the lifecycle of a service


The lifecycle of a service is much simpler than that of an activity. However, it's even moreimportant that you pay close attention to how your service is created and destroyed because aservice can run in the background without the user being aware.

The service lifecycle—from when it's created to when it's destroyed—can followeither of these two paths:

  • A started service

    The service is created when another component calls startService(). The service then runs indefinitely and muststop itself by calling stopSelf(). Another component can also stop theservice by callingstopService(). When the service is stopped, the system destroys it.

  • A bound service

    The service is created when another component (a client) calls bindService(). The client then communicates with the servicethrough an IBinder interface. The client can close the connection by callingunbindService(). Multiple clients can bind tothe same service and when all of them unbind, the system destroys the service. The servicedoesnot need to stop itself.

These two paths are not entirely separate. You can bind to a service that is alreadystarted withstartService(). For example, you canstart a background music service by callingstartService() with anIntent that identifies the music to play. Later,possibly when the user wants to exercise some control over the player or get information about thecurrent song, an activity can bind to the service by calling bindService(). In cases such as this, stopService() orstopSelf() doesn't actually stop the service until all of the clients unbind.

Implementing the lifecycle callbacks

Like an activity, a service has lifecycle callback methods that you can implement to monitorchanges in the service's state and perform work at the appropriate times. The following skeletonservice demonstrates each of the lifecycle methods:

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: Unlike the activity lifecycle callback methods, you arenot required to call the superclass implementation of these callback methods.

Figure 2. The service lifecycle. The diagram on the leftshows the lifecycle when the service is created withstartService() and the diagram on the right shows the lifecycle when the service is createdwithbindService().

Figure 2 illustrates the typical callback methods for a service. Although the figure separatesservices that are created bystartService() from thosecreated bybindService(), keepin mind that any service, no matter how it's started, can potentially allow clients to bind to it.A service that was initially started withonStartCommand() (by a client callingstartService())can still receive a call toonBind() (when a client callsbindService()).

By implementing these methods, you can monitor these two nested loops of the service'slifecycle:

Note: Although a started service is stopped by a call toeitherstopSelf() orstopService(), there is not a respective callback for theservice (there's noonStop() callback). Unless the service is bound to a client,the system destroys it when the service is stopped—onDestroy() is the only callback received.

For more information about creating a service that provides binding, see the Bound Services document,which includes more information about the onRebind()callback method in the section aboutManaging the lifecycle ofa bound service.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值