`
zhengjj_2009
  • 浏览: 149261 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Android Service 官网资料的阅读和翻译

 
阅读更多

参考页面地址 http://developer.android.com/guide/components/services.html

 

A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue 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 might handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.

服务是一种应用组件,它能在后台执行长时间的操作,可以不提供一个用户界面。另一个应用组件可以启动一个服务,该服务将继续运行在后台,即使用户切换到另一个应用。
此外,一个应用组件可以绑定到一个服务上和该服务交互,甚至进行进程间的通信。例如一个服务可以处理网络事务处理、播放音乐、执行文件I/O操作或与一个内容提供者进行交互,以上所有这一切都在后台进行。

 

A service can essentially take two forms:从本质上来说服务只能采取两种形式(以两种形式存在)

Started(已启动)
A service is "started" when an application component (such as an activity) starts it by calling startService(). Once 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 might download or upload a file over the network. When the operation is done, the service should stop itself.
当一个应用组件(例如一个activity)通过调用startService()启动一个服务,该服务就是"已启动"状态。服务一旦启动后,它能长期运行在后台,即使调用它的应用组件已经被销毁了,它还能在后台继续进行。
一般来说,一个已启动的服务执行一个单一的操作,并不返回一个结果给调用者,例如,该服务可以通过网络下载或上传文件,当这些操作完成后,服务就应当自行停止。

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, get 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.
当一个应用组件通过调用bindService()将自己绑定到一个服务上,该服务就处于"已绑定"的状态。一个"已绑定"状态的服务可以提供一个C/S的接口,允许应用组件与服务进行交互,发送请求和获取结果,
甚至可以通过IPC技术,跨进程完成这些操作。只要另一个应用组件绑定到该服务,该"已绑定"服务就能运行。多个应用组件可以一次绑定到该服务,但当所有的应用组件与该服务解除绑定后,该服务就被销毁了。

 

Although this documentation generally discusses these two types of 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 callback methods: onStartCommand() to allow components to start it and onBind() to allow binding.
虽然这份文档主要是单独讨论服务的两者类型,但是我们所开发出来的服务可以以两者方式运行。服务可以被启动(长时间运行)也可以运行绑定,这取决于你是否实现一组回调方法:onStartCommand()来运行组件启动服务,onBind()运行服务被绑定

 

Regardless of whether your application is started, bound, or both, any application component can use the service (even from a separate application), in the same way that any component can use an activity—by starting it with an Intent. However, you can declare the service as private, in the manifest file, and block access from other applications. This is discussed more in the section about Declaring the service in the manifest.
无论我们的服务应用是被启动还是被绑定(后者两者方式都有),任何一个应用组件都能使用我们的服务(即使是从一个另一个单独的应用),使用方式与任何一个应用组件通过Intent方式启动一个Activity的方式一样。
但是我们在manifest文件中可以将我们的服务申明为private,阻止其他应用对它的访问。这些问题在"Declaring the service in the manifest"将继续更多的讨论。

 

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). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work. By using a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the application's main thread can remain dedicated to user interaction with your activities.
注意:一个服务运行在它的宿主进程的主线程中。服务不能创建自己的线程,不能运行一个单独的进程中,除非我们具体指定外。
这也就是说:如果我们的服务想做一些CPU密集的工作,或阻止一些操作(例如MP3重复播放或联接网络),我们应该在该服务内创建一个新的线程来完成上诉工作。通过使用单独的线程,我们可以降低(ANR应用无响应)错误的风险,应用程序的主线程可以专注于与我们的Activity的用户交互。

 


The Basics 基础知识
To create a service, you must create a subclass of Service (or one of its existing subclasses). In your implementation, you need to override some callback methods that handle key aspects of the service lifecycle and provide a mechanism for components to bind to the service, if appropriate. The most important callback methods you should override are:
要创建一个服务,我们必须创建一个Service的子类(或者已经存在的子类的子类)。在我们的具体实现中,我们需要覆盖重写一些回调方法来适当处理服务生命周期的重要信息,为应用组件提供一套机制来绑定到该服务上。需要重写的回调方法有以下几个最重要:

 

onStartCommand()
The system calls this method when another component, such as an activity, requests that the service be started, by calling startService(). Once 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 done, by calling stopSelf() or stopService(). (If you only want to provide binding, you don't need to implement this method.)
当另一个组件(例如一个Activity)通过调用startService()请求服务应该启动了,系统会调用onStartCommand()方法。一旦该方法被执行,服务就处于"已启动"的状态,能长期在后台运行。如果我们实现了该方法,当服务的工作已经完成,我们就必须调用stopSelf()或stopService()来停止服务。(如果我们只想提供绑定功能,我们就不必实现覆写该方法。)

 

onBind()
The system calls this method when another component wants to bind with the service (such as to perform RPC), by calling bindService(). 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, but if you don't want to allow binding, then you should return null.
当另一个应用组件通过调用bindService()方法,想与服务实现绑定(例如实现RPC的功能),系统就会调用该方法。在实现该方法中,我们必须提供一个接口返回一个IBinder接口,这样客户端可以使用这个接口与服务进行通信。我们经常需要实现该方法,但如果我们不运行绑定,那么我们就返回null即可。

 

onCreate()
The system calls this method when the service is first created, to perform one-time setup procedures (before it calls either onStartCommand() or onBind()). If the service is already running, this method is not called.
当服务第一次被创建,执行一次性的安装程序(在该服务调用onStartCommand()或onBind()之前),系统会调用该方法。如果服务已经处于运行状态,那么该方法就不会被调用。

 

onDestroy()
The system calls 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, receivers, etc. This is the last call the service receives.
当服务不在使用并且即将被销毁,系统会调用该方法。我们的服务应该首先这个方法,去清理任何资源,例如线程、注册的监听器、接收者等。这个方式是该服务接收到的最后一个调用方法。


 If a component starts the service by calling startService() (which results in a call to onStartCommand()), then the service remains running until it stops itself with stopSelf() or another component stops it by calling stopService().
 如果一个组件通过调用startService()启动服务(会导致去调用onStartCommand()),然后服务就一直处于运行状态,知道它自己调用stopSelf()停止自己,或者另一个方法调用stopService()停止掉该服务。
 
 
 If a component calls bindService() to create the service (and onStartCommand() is not called), then the service runs only as long as the component is bound to it. Once the service is unbound from all clients, the system destroys it.
 如果一个组件调用了bindService()来创建一个服务(同时没有调用onStartCommand()), 那么只要组件实现了与该服务的绑定,该服务就开始运行。一旦该服务与其他所有客户端实现了解除绑定, 系统就会销毁掉该服务。

 

The Android system will force-stop 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, then it's less likely to be killed, and if the service is declared to run in the foreground (discussed later), then it will almost never be killed. Otherwise, if the service was started and is long-running, then the system will lower its position in the list of background tasks over time and the service will become highly susceptible to killing—if your service is started, then you must design it to gracefully handle restarts by the system. If the system kills your service, it restarts it as soon as resources become available again (though this also depends on the value you return from onStartCommand(), as discussed later). For more information about when the system might destroy a service, see the Processes and Threading document.
当内存比较低,必须为获得用户焦点的Activity 回收系统资源,系统会强行停止一个服务。如果该服务与该获得用户焦点的Activity实现了绑定,那么它被kill掉的可能性比较小。如果该服务被申明将运行在前台,那么它大部分不会被kill掉。否则,如果服务被启动且长时间运行,随着时间的推移,系统会降低该服务在后台任务列表的排行表的位置,那么该服务有可能被kill掉。  


如果我们的服务处于"已启动"的状态,我们一定要将它实现较好地处理由系统的重启功能。如果系统kill掉我们的服务,只要系统资源又一次可以满足条件,系统将会重启我们的服务(这也取决于onStartCommand()的返回值,这在后面将进一步讨论)。

In the following sections, you'll see how you can create each type of service and how to use it from other application components.

 

Should you use a service or a thread? 我们应该使用Service或Thread?

A service is simply a component that can run in the background even when the user is not interacting with your application. Thus, you should create a service only if that is what you need.
Service仅仅是一个运行在后台的组件,在其运行期间用户甚至可以不用和应用程序交互。因此只有服务是我们所需的时候,我们才应该创建一个服务。

 

If you need to perform work outside your main thread, but only while the user is interacting with your application, then you should probably instead create a new thread and not a service. For example, if you want to play some music, but only while your activity is running, you might create a thread in onCreate(), start running it in onStart(), then stop it in onStop(). Also consider using AsyncTask or HandlerThread, instead of the traditional Thread class. See the Processes and Threading document for more information about threads.
如果我们需要在主线程外执行一些操作,但只能在与用户正在于我们的应用程序交互的时候进行,我们应该创建一个新的线程而不是一个服务。例如我们想播放一些音乐,但同时我们的activity也在运行,这时我们可以在onCreate()创建一个线程,在onStart()中开始运行该线程,在onStop()方法中停止该线程。同时应该考虑使用AsyncTask或HandlerThread,而非传统的Thread类。

 

Remember that if you do use a service, it still runs in your application's main thread by default, so you should still create a new thread within the service if it performs intensive or blocking operations.
需要记住的是:如果我们确实使用了一个服务,默认的情况下,服务依然运行在我们应用的主线程中。所以如果服务执行一些密集或阻塞性的操作时,我们仍然应该在服务内创建一个线程


 In the following sections, you'll see how you can create each type of service and how to use it from other application components.(此句比较简单,不翻译了。)

 

Declaring a service in the manifest (在mannifest中声明一个服务)

Like activities (and other components), you must declare all services in your application's manifest file.

To declare your service, add a <service> element as a child of the <application>element. For example:  

在<application>元素添加一个<service>元素作为其子节点

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

There are other attributes you can include in the <service> element to define properties such as permissions required to start the service and the process in which the service should run. The android:nameattribute is the only required attribute—it specifies the class name of the service. Once you publish your application, you should not change this name, because if you do, you might break some functionality where explicit intents are used to reference your service (read the blog post, Things That Cannot Change).

<service>元素中可以加入其它属性来定义 <service>元素的属性,例如启动服务或进程所需的权限属性,属性android:name是唯一一个所必须的属性,它指定了该服务的类名。一旦我们发布了自己的应用,我们就不能修改这个名字,因为如果修改了名字,我们将可能破坏显示意图调用该服务的功能。

 

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

 

Just like an activity, a service can define intent filters that allow other components to invoke the service using implicit intents. By declaring intent filters, components from any application installed on the user's device can potentially start your service if your service declares an intent filter that matches the intent another application passes to startService().

和activity一样,service可以定义Intent过滤器,从而允许其他组件使用隐式意图调用该服务。通过声明意图过滤器,只要你的服务声明的Intent过滤器匹配了另一个应用通过startService()传递过来的Intent,安装在用户手机上的任何一个应用的组件都有可能在将来某个时刻启动你的服务。

 

If you plan on using your service only locally (other applications do not use it), then you don't need to (and should not) supply any intent filters. Without any intent filters, you must start the service using an intent that explicitly names the service class. More information about starting a service is discussed below.

Additionally, you can ensure that your service is private to your application only if you include the android:exportedattribute and set it to "false". This is effective even if your service supplies intent filters.

For more information about creating intent filters for your service, see the Intents and Intent Filtersdocument.

android:exported设置为flase,将设置该服务为私有类型。

 

Creating a Started Service

 

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

 

When a service is started, it has a lifecycle that's independent(独立于) of the component that started it and the service can run in the background indefinitely, even if the component that started it is destroyed. As such, the service should stop itself when its job is done by calling stopSelf(), or another component can stop it by calling stopService().

 

An application component such as an activity can start the service by calling startService() and passing an Intentthat specifies the service and includes any data for the service to use. The service receives this Intent in the onStartCommand() method.

 

For instance, suppose(假设) an activity needs to save some data to an online database. The activity can start a companion(同行) service and deliver it the data to save by passing an intent to startService(). The service receives the intent in onStartCommand(), connects to the Internet and performs the database transaction. When the transaction is done, the service stops itself and it is destroyed.

 

Caution: A services runs in the same process as the application in which it is declared and in the main thread of that application, by default. So, if your service performs intensive or blocking operations while the user interacts with an activity from the same application, the service will slow down activity performance. To avoid impacting application performance, you should 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 that you create a new thread in which to do all the service's work, because the service uses your application's main thread, by default, which could slow the performance of any activity your application is running.
IntentService
This is a subclass of Service that uses a worker thread to handle all start requests, one at a time. This is the best option if you don't require that your service handle multiple requests simultaneously. All you need to do is implement onHandleIntent(), which receives the intent for each start request so you can do the background work.

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

Extending the IntentService class

Because most started services don't need to handle multiple requests simultaneously (which can actually be a dangerous multi-threading scenario), it's probably best if you implement your service using the IntentService class.

The IntentService does the following:

  • Creates a default worker thread that executes all intents delivered to onStartCommand() separate from your application's main thread.
  • Creates a work queue that passes one intent at a time to your onHandleIntent() implementation, so you never have to worry about multi-threading.
  • Stops the service after all start requests have been handled, so you never have to callstopSelf().
  • Provides 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.

All this adds up to the fact that all you need to do is implement onHandleIntent() to do the work provided by the client. (Though, 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.
      long endTime = System.currentTimeMillis() + 5*1000;
      while (System.currentTimeMillis() < endTime) {
          synchronized (this) {
              try {
                  wait(endTime - System.currentTimeMillis());
              } catch (Exception e) {
              }
          }
      }
  }
}

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(), or onDestroy(), be sure to call the super implementation, so that the IntentService can properly handle the life of the worker thread.

For example, onStartCommand() must return the default implementation (which is how the intent gets 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 method from which you don't need to call the super class is onBind() (but you only need to implement that if your service allows binding).

In the next section, you'll see how the same kind of service is implemented when extending the base Service class, which is a lot more code, but which might be appropriate if you need to handle simultaneous start requests.

Extending the Service class

As you saw in the previous section, using IntentService makes your implementation of a started service very simple. If, however, you require your service to perform multi-threading (instead of processing start requests through a work queue), then you can extend the Service class to handle each intent.

For comparison, the following example code is an implementation of the Service class that performs the exact same work as the example above using IntentService. That is, for each start request, it uses a worker thread to perform the job 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.
          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(); 
  }
}

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 what this example does, but if that's what you want, then you can create a new thread for each request and run them right away (instead of waiting for the previous request to finish).

Notice that the onStartCommand() method must return an integer. The integer is a value that describes how the system should continue the service in the event that the system kills it (as discussed above, the default implementation for IntentService handles this for you, though you are able to modify it). The return value from onStartCommand() must be one of the following constants:

START_NOT_STICKY
If the system kills the service after onStartCommand() returns, do not recreate the service, unless there are pending intents to deliver. This is the safest option to avoid running your service when not necessary and 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 a null intent, unless there were pending intents to start the service, in which case, those intents are delivered. This is suitable for media players (or similar services) that are not executing commands, but 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 the service. Any pending intents are delivered in turn. This is suitable for services that are actively 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 each constant.

Starting a Service

You can start a service from an activity or other application component by passing anIntent (specifying the service to start) to startService(). The Android system calls the service's onStartCommand() method and passes it the Intent. (You should never call onStartCommand() directly.)

For example, an activity can start the example service in the previous section (HelloSevice) using an explicit intent with startService():

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

The startService() method returns immediately and the Android system calls the service's onStartCommand() method. If the service is not already running, the system first calls onCreate(), then calls onStartCommand().

If the service does not also provide binding, the intent delivered with startService() is the only mode of communication between the application component and the service. However, if you want the service to send a result back, then the client that starts the service can create a PendingIntent for a broadcast (with getBroadcast()) and deliver it to the service in the Intent that starts the service. The service can then use the broadcast to deliver a result.

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

Stopping a service

A started service must manage its own lifecycle. That is, the system does not stop or destroy the service unless it must recover system memory and the service continues to run after onStartCommand() returns. So, the service must stop itself by calling stopSelf() or another component can stop it by calling stopService().

Once requested to stop with stopSelf() or stopService(), the system destroys the service as soon as possible.

However, if your service handles multiple requests to onStartCommand() concurrently, then you shouldn't stop the service when you're done processing a start request, because you might have since received a new start request (stopping at the end of the first request would terminate the second one). To avoid this problem, you can use stopSelf(int) to ensure that your request to stop the service is always based on the most recent start request. That is, when you call stopSelf(int), you pass the ID of the start request (the startIddelivered to onStartCommand()) to which your stop request corresponds. Then if the service received a new start request before you were able to call stopSelf(int), then the ID will not match and the service will not stop.

Caution: It's important that your application stops its services when it's done working, to avoid wasting system resources and consuming battery power. If necessary, other components can stop the service by calling stopService(). Even if you enable binding for the service, you must always stop the service yourself if it ever received a call to onStartCommand().

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

Creating a Bound Service


A bound service is one that allows application components to bind to it by calling bindService() in order to create a long-standing connection (and generally does not allow components to start it by calling startService()).

You should create a bound service when you want to interact with the service from activities and other components in your application or to expose some of your application's functionality to other applications, through interprocess communication (IPC).

To create a bound service, you must implement the onBind() callback method to return an IBinder that defines the interface for communication with the service. Other application components can then callbindService() to retrieve the interface and begin calling methods on the service. The service lives only to serve the application component that is bound to it, so when there are no components bound to the service, the system destroys it (you do not need to stop a bound service in the way you must when the service is started through onStartCommand()).

To create a bound service, the first thing you must do is define the interface that specifies how a client can communicate with the service. This interface between the service and a client must be an implementation of IBinder and is what your service must return from the onBind() callback method. Once the client receives the IBinder, it can begin interacting with the service through that interface.

Multiple clients can bind to the service at once. When a client is done interacting with the service, it calls unbindService() to unbind. Once 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 more complicated than a started service, so the bound service discussion appears in a separate document about Bound Services.

Sending Notifications to the User


Once running, a service 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 a moment then disappears, while a status bar notification provides an icon in the status bar with a message, 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 when some background work has completed (such as a file completed downloading) and the user can now act on it. When the user selects the notification from the expanded view, the notification can start an activity (such as to view 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's considered to be something the user is actively aware of and thus not a candidate for the system to kill when low on memory. A foreground service must provide a notification for the status bar, which is placed under the "Ongoing" heading, which means that the notification cannot be dismissed unless the service is either stopped or removed from the foreground.

For example, a music player that plays music from a service should be set to run in the foreground, because the user is explicitly aware of its operation. The notification in the status bar might indicate the current song and allow the 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: an integer that uniquely identifies the notification and the Notification for the status bar. 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, notification);

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

Note: The methods startForeground() and stopForeground() were introduced in Android 2.0 (API Level 5). In order to run your service in the foreground on older versions of the platform, you must use the previous setForeground() method—see the startForeground() documentation for information about how to provide backward compatibility.

For more information about notifications, see Creating Status Bar Notifications.

Managing the Lifecycle of a Service


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

The service lifecycle—from when it's created to when it's destroyed—can follow two different paths:

  • A started service

    The service is created when another component calls startService(). The service then runs indefinitely and must stop itself by calling stopSelf(). Another component can also stop the service by calling stopService(). 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 service through an IBinder interface. The client can close the connection by callingunbindService(). Multiple clients can bind to the same service and when all of them unbind, the system destroys the service. (The service does not need to stop itself.)

These two paths are not entirely separate. That is, you can bind to a service that was already started with startService(). For example, a background music service could be started by calling startService() with an Intent that identifies the music to play. Later, possibly when the user wants to exercise some control over the player or get information about the current song, an activity can bind to the service by calling bindService(). In cases like this, stopService() or stopSelf() does not actually stop the service until all clients unbind.

Implementing the lifecycle callbacks

Like an activity, a service has lifecycle callback methods that you can implement to monitor changes in the service's state and perform work at the appropriate times. The following skeleton service 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.

分享到:
评论

相关推荐

    Android4 Service中文指南

    个人原创 基于Android4.0 目前最全面的对于Android Service的中文介绍 和英文文档翻译

    android开发资料大全

    Android 之 AIDL 和远程 Service 调用 Android 相对布局技巧 android开发环境之Logcat(日志)教程实例汇总 android网络通信之socket教程实例汇总 AsyncTask进度条加载网站数据到ListView 命令行开发、编译、打包...

    Android API中文翻译(6)

    android.accessibilityservice android.bluetooth android.content android.location android.media android.net android.os android.text android.view android.view.inputmethod android.widget

    精通ANDROID 3(中文版)1/2

    1.5.5 Android Service组件  1.5.6 Android媒体和电话组件  1.5.7 Android Java包  1.6 利用Android源代码  1.7 本书的示例项目  1.8 小结  第2章 设置开发环境  2.1 设置环境  2.1.1 下载JDK 6  ...

    Android使用Service实现简单音乐播放实例

    Service翻译成中文是服务,熟悉Windows 系统的同学一定很熟悉了。Android里的Service跟Windows里的Service功能差不多,就是一个不可见的进程在后台执行。  Android中的服务,它与Activity不同,它是不能与用户交互...

    Android深入浅出之Binder机制.pdf

    Android系统最常见也是初学者最难搞明白的就是Binder了,很多很多的Service就是通过Binder机制来和客户端通讯交互的。所以搞明白Binder的话,在很大程度上就能理解程序运行的流程。我们这里将以MediaService的例子来...

    基于android手机通讯录的设计与实现中英文翻译

    基于android手机通讯录的设计与实现中英文翻译 摘要 随着手机市场的发展,3G手机逐渐占领手机市场,3G手机系统开发也成为市场上的热门技术…… 关键字:应用组件 关闭组件 manifest文件 Intent过滤器 activity ...

    Google Android SDK开发范例大全(PDF高清完整版1)(4-1)

    Google Android SDK开发范例大全(完整版)共4个分卷 目录 第1章 了解.深入.动手做. 1.1 红透半边天的Android 1.2 本书目的及涵盖范例范围 1.3 如何阅读本书 1.4 使用本书范例 1.5 参考网站 第2章 Android初体验 2.1...

    Google Android SDK开发范例大全(第3版) 1/5

    《Google Android SDK开发范例大全(第3版)》内容由Android的基础知识到实际开发应用,结构清晰、语言简洁,非常适合Android的初学者和Android的进阶程序开发者阅读参考。 编辑本段 编辑推荐 《Google Android SDK...

    Google Android SDK开发范例大全(PDF完整版4)(4-4)

    Google Android SDK开发范例大全(完整版)共4个分卷 目录 第1章 了解.深入.动手做. 1.1 红透半边天的Android 1.2 本书目的及涵盖范例范围 1.3 如何阅读本书 1.4 使用本书范例 1.5 参考网站 第2章 Android初体验 2.1...

    精通Android 3 (中文版)2/2

    1.5.5 Android Service组件  1.5.6 Android媒体和电话组件  1.5.7 Android Java包  1.6 利用Android源代码  1.7 本书的示例项目  1.8 小结  第2章 设置开发环境  2.1 设置环境  2.1.1 下载JDK 6  ...

    Google Android SDK开发范例大全(第3版) 4/5

    《Google Android SDK开发范例大全(第3版)》内容由Android的基础知识到实际开发应用,结构清晰、语言简洁,非常适合Android的初学者和Android的进阶程序开发者阅读参考。 编辑本段 编辑推荐 《Google Android SDK...

    Google Android SDK开发范例大全(第3版) 3/5

    《Google Android SDK开发范例大全(第3版)》内容由Android的基础知识到实际开发应用,结构清晰、语言简洁,非常适合Android的初学者和Android的进阶程序开发者阅读参考。 编辑本段 编辑推荐 《Google Android SDK...

    Google Android SDK开发范例大全(第3版) 5/5

    《Google Android SDK开发范例大全(第3版)》内容由Android的基础知识到实际开发应用,结构清晰、语言简洁,非常适合Android的初学者和Android的进阶程序开发者阅读参考。 编辑本段 编辑推荐 《Google Android SDK...

    Google Android SDK开发范例大全(PDF高清完整版3)(4-3)

    Google Android SDK开发范例大全(完整版)共4个分卷 目录 第1章 了解.深入.动手做. 1.1 红透半边天的Android 1.2 本书目的及涵盖范例范围 1.3 如何阅读本书 1.4 使用本书范例 1.5 参考网站 第2章 Android初体验 2.1...

    unlocking_android.pdf.7z

    今天我要介绍另一本Android的教程,本书的介绍在亚马逊上一位读者的评论讲的非常详细到位,在此我就借用这位读者的评论将其翻译给大家看看吧,同样,我也提供这本书电子版的下载。 “这是任何一个要进行Android开发...

    Google Android SDK开发范例大全的目录

    8.7 手机气象局,实时卫星云图——HttpURLConnection与URLConnection和运行线程 8.8 通过网络播放MP3——Runnable存储FileOutputStream技巧 8.9 设置远程下载音乐为手机铃声——RingtoneManager与铃声存放路径 8.10 ...

Global site tag (gtag.js) - Google Analytics