Service 服務

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
Service是一個長期運行在後臺,並不提供界面的應用組件。其他組件可以啓動一個服務,並且即使用戶切換到其他的應用,該服務仍可在後臺繼續運行。另外,組件可以把某個服務邦定到自己,來與其交互通信,甚至包括執行進程間通信(IPC).例如,某個服務可能在處理來自後臺的,網絡傳輸,放音樂,執行文件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.
當某個應用組件調用startService()方法啓動服務時,服務就處於啓動態(started).一旦啓動,即使啓動服務的組件已銷燬,該服務仍能無限的運行在後臺.   一般,一個啓動的服務只執行單一操作,且並不返回結果給它的調用者.比如,某服務可能下載或上傳文件到網上,當操作完成,該服務應該自己停止自己.
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()方法,邦定服務,該服務就處理邦定態。一個邦定的服務提供一個客戶端服務接口,所有的組件通過這個接口與服務交流,發送請求,獲取結果,並且甚至是進程間通信。只有其他應用組件邦定到該服務,該邦定服務才運行。可以同時邦定多個組件到該服務,但只有當所有邦定的組件都鬆邦後,該服務才銷燬。
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意圖啓動。但是,你可以在manifest文件中,將服務聲明爲私有,並阻止來自其他應用的訪問。關於此的詳細討論,在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),並且能讓應用的主線程保持處理,用戶與你的活動之間的交互操作.
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.)
當其他的組件,比如某個活動,調用startService()方法請求啓動服務時,系統調用這個方法.一旦這個方法執行,該服務就處於已啓動狀態,並且無限循環的運行在後臺。如果你實現這個方法,當服務的工作處理完成後,你要負責停止這個服務.通過調用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()方法,想邦定到該服務時,系統調用該方法。在你的本方法實現中,你必須提供一個接口返回一個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.
只有當缺少內存及必須爲用戶的焦點活動恢復系統資源時,Android系統將強制停止一個服務。如果服務被邦定到一個捅有用戶焦點的活動,那麼它很少會被殺掉,並且如果該服務被聲明成run in the foreground (運行在前臺,後面討論),那麼該服務幾乎不被殺掉。否則,如果服務開啓後,長期在運行,那麼隨着時間的延長,系統會降低它在後臺任務列表中的位置,並將變得極有可能被殺掉-如果你的服務被開啓了,那麼你應把它(服務)設置成完全可以由系統重啓.如果系統殺掉了你的服務,一旦資源變得可能,系統將儘可能重啓它(但這仍然依賴於你從onStartCommand()方法返回的值,後面討論)。關於系統什麼時候可能會銷燬服務的,詳細信息請看Processes and Threading文檔.
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在manifest文檔中聲明服務
Like activities (and other components), you must declare all services in your application's manifest file.跟活動一樣(及其他組件),你必須在你的應用的manifest文件中,聲明所有的服務.
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:name attribute 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>元素中包含一些其他的屬性,來定義像請求開啓服務的權限和該服務應該運行的進程。android:name屬性是唯一必須要求的屬性—它指定了服務的類名.一旦你的應用發佈了,你應不要改變這個名字,因爲如果你改變了這個名字,可能會破壞那些顯式的引用你的服務的功能(讀取博文,一些其他不改變的東西Things That Cannot Change)。
See the <service> element reference for more information about declaring your service in the manifest.
更多關於在manifest中聲明你的服務的信息,請參考<service> 元素索引.
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一樣,服務也可以通過定義意圖過濾器,讓其他組件使用隱式意圖來調用服務。通過聲明意圖過濾器,如果你聲明的意圖過濾器與其他應用傳給startService()方法的意圖相匹配,則安裝在用戶設備上的任何應用的組件潛在的可啓動你的服務.
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.
如果你僅讓你的服務在局部使用(其他的應用不能使用它),那麼你不需要提供一個意圖過濾器。因爲沒有任何意圖過濾器,你必須使用顯式的指出服務類名的意圖來啓動該服務。下面的starting a service 中將詳細討論.
Additionally, you can ensure that your service is private to your application only if you include the android:exported attribute and set it to "false". This is effective even if your service supplies intent filters.
另外,只要你包含了屬性,並設爲"false",那麼就能確保你的服務僅爲你的應用私有。這樣即使你的服務提供了意圖過濾器,但你的服務仍然僅爲你的應用私有.
For more information about creating intent filters for your service, see the Intents and Intent Filters document.
關於爲服務創建意圖過濾器,請看Intents and Intent Filters文檔.
Creating a Started Service創建啓動服務
A started service is one that another component starts by calling startService(), resulting in a call to the service's onStartCommand() method.
其他組件調用startService()方法,並導致服務的onStartCommand()方法被調用,這就是一個啓動的服務。
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().
當一個服務啓動後,它就捅有了獨立於開啓它的組件的生命週期,並且即使開啓它的組件被銷燬,它也可以在無限循環的運行在後臺。因此當服務的工作處理完成後,它應該自己調用stopSelf()方法結束自己,或者其他的組件調用stopService()方法停止服務。
An application component such as an activity can start the service by calling startService() and passing an Intent that specifies the service and includes any data for the service to use. The service receives this Intent in the onStartCommand() method.
某個應用組件,比如activity,可以將一個包含指定服務及服務要用的任意數據的Intent意圖,傳給startService()方法,來啓動一個服務。該服務將會在onStartCommand()方法中接收到這個Intent意圖.
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.
比如,假設一個活動需要保一些存數到在線數據庫。這個活動可以把要保存的數據傳給startService()方法,來開啓一個協助服務,該服務在onStartCommand()方法接收到這個意圖,連接到網上,並處理數據庫交換。當交換完成,該服務停止它自己並銷燬自己.
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.
這是一個Service類的子類,它使用一個工人線程處理所有發起的服務,一次處理一個。如果你不想讓你的線程同時處理多個服務,這是最好的選擇。你所需要做的所有事情,是實現onHandleIntent()方法。在這個實現中接收每個發起請求的意圖,以便你做些後臺處理。
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.
因爲多數啓動的服務不需要同時處理多個請求(實際上同時處理多個請求的情況是多線程),所以可能用IntentService這個類,來實現你的服務是最好的選擇。
The IntentService does the following:這個類處理如下事情:
Creates a default worker thread that executes all intents delivered to onStartCommand() separate from your application's main thread.
創建一個獨立於你應用的主線程的工作線程,在這個工作線程中處理所有傳給onStartCommand()方法的意圖
Creates a work queue that passes one intent at a time to your onHandleIntent() implementation, so you never have to worry about multi-threading.
創建一個工作隊列,每次傳一個意圖給你的onHandleIntent()方法實現,所以你永不必擔心多線程的問題
Stops the service after all start requests have been handled, so you never have to call stopSelf().
在所有發起的請求處理完後停止服務,所以你永不必調用stopSelf()方法.
Provides default implementation of onBind() that returns null.
提供一個默認的onBind()方法的實現,該實現返回null.
Provides a default implementation of onStartCommand() that sends the intent to the work queue and then to your onHandleIntent() implementation.
提供一個默認的onStartCommand()方法的實現,來發送意圖到工作隊列,然後(由工作隊列)發到你的onHandleIntent()方法的實現
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.)
所有這些都基於:實現onHandleIntent()方法,來處理客戶端的請求的工作。(因此,你還需要爲服務提供一個小構造器).
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() &lt; 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.
所有你需要做的是:一個構造器和一個onHandleIntent()方法的實現.
如果你還想要複寫其他的回調方法,比如onCreate(), onStartCommand(), onDestroy(),。確保調用了超類實現,以便IntentService類可以正確處理工作線程的生命週期.
For example, onStartCommand() must return the default implementation (which is how the intent gets delivered to onHandleIntent()):
比如,onStartCommand()方法必須返回默認實現(這是意圖傳遞到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).
除了onHandleIntent()方法之外,onBind()方法是唯一不需要調用的超類的方法(但如果你的服務允許邦定,你只需實現它)
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.
在下面的部分,你將明白當繼承了Service基類時,怎樣實現相同的服務;這種方代碼稍多一些,但是如果需要處理同時發起的多個請求,這種方式可能理適合您。
Extending the Service class繼承服務Service類
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.
就如上面你所看到的,使用IntentService類,你可以簡單的啓動服務。但,若要求你的服務處理多線程(不是用一個工作隊列來處理啓動請求),那麼可以繼承Service類來處理每個意圖.
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.
通過比較,下面的例子是實現Service類,與上面使用IntentService類處理的工作完全相同。對於每個發起的請求,它使用一個工作線程執行工作,並且每次只處理一個.
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() &lt; 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.如你所見,它比使用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).
然而,因爲你可自己處理每個對onStartCommand()的調用,所以你可以同時執行多個請求。這段例子沒有那樣做,但是如果你想要那樣做,那麼可以爲每個請求創建一個新線程,並且以正確的方法運行它。(而不是等到前一個請求執行完成.)
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:
注意,方法必須返回一個整數值。這個整數值,描述了在系統殺掉本服務的情況下,系統應該如何繼續該服務(如上所討論的,IntentService類的默認實現爲你處理了這個事情,但你也可以修改它)。從onStartCommand()該方法返回的值必須是下面常量中的一個.
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.
在onStartCommand()返回後,如果系統殺掉了該服務,除非有掛起的意圖要傳送,系統不重創建服務。這是避免不必運行你的服務,及你的應用可以簡單的重新開始沒有完成的工作時的一種安全的選擇。
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.
     在onStartCommand()返回後,如果系統殺掉了該服務,重創建服務並調用onStartCommand()方法,但是不傳遞最後的意圖.而是系統傳一個null,給調用的onStartCommand().除非有掛起的意圖啓動服務,那樣的話,這些意圖被傳送。這適用於類於多媒體播放器的服務,它們不需要執行命令,但是要無限運行並等待工作。
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.
在onStartCommand()返回後,如果系統殺掉了該服務,重新創建服務並調用onStartCommand()方法,並將最後一個傳給服務的意圖傳給onStartCommand()方法。這適合那要立即恢復並積極主動執行工作的服務,比如下載文件。關於這個返回值的詳細情況,請看每個常量鏈接引用的文檔
Starting a Service啓動服務
You can start a service from an activity or other application component by passing an Intent (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.)
你可以通過將一個Intent意圖傳給startService()方法,從某個活動或其他應用組件中啓一個服務.Android系統將調用服務的onStartCommand()方法,並將一個Intent意圖傳給它。(你應該永遠不要直接調用onStartCommand()方法)
For example, an activity can start the example service in the previous section (HelloSevice) using an explicit intent with startService():
例如,一個活動可以給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().
startService()方法立即返回,並且系統會調用onStartCommand()方法,如果服務沒有正在運行,系統首先調用onCreate(),方法,然後調用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.
如果服務還沒有邦定,使用startService()方法傳送意圖,是應用組件與服務通信的唯一模式.然而,如果你想要服務返回一個結果,那麼啓動服務的客戶端,可以創建一個用於廣播的PendingIntent掛起意圖,並且在啓動服務的Intent意圖中,將這個掛起意圖傳給服務.然後服務就可以用這個廣播來傳遞一個結果.
Multiple requests to start the service result in multiple corresponding calls to the service's onStartCommand(). However, only one request to stop the service (with stopSelf() or stopService()) is required to stop it.
對啓動服務的多個請求,會相應的導致多次調用服務的方法。然而,只有一個請求停止服務(stopSelf() or stopService())請求停止它。
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().
一個啓動的服務必須能管理它自己的生命週期。那就是,除非系統要收復系統內存,系統不停止和銷燬服務,並且在onStartCommand()方法返回後能繼續運行.所以,服務必須調用stopSelf()方法停止自己,或者其他組件調用stopService()方法停止它.
Once requested to stop with stopSelf() or stopService(), the system destroys the service as soon as possible.
一旦用stopSelf()或stopService()方法,發出停止請求,系統將儘可能快的停止服務.
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 startId delivered 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.
然而,如果你的服務正在同時處理多個發給onStartCommand()方法的請求,那麼你不應該在處理完一個發起的請求(a start request)後停止服務,因爲你可已接到一個新的發起請求(在第一個請求之後停止可能會終結第二個請求).爲了避免這個問題,你可以用stopSelf(int)方法,確保你的停止服務的請求,總是基於最後發起的請求的。那就是,當你調用stopSelf(int)方法時,傳一個請求停止相應的服務的ID。然後如果服務在你能調用stopSelf(int)方法之前,接收到一個新發起的請求,那麼這個ID將不會匹配,並且服務將不停止.
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().
注意:當服務處理完工作後,你的應用停止它很重要,以避免浪費系統資源和消耗電池。如果必要的話,其他組件可以用stopService()方法停止它。即使你允許邦定,但如果你曾經收到一個onStartCommand()調用,你必須總是自己停止服務.
For more information about the lifecycle of a service, see the section below about Managing the Lifecycle of a Service.
關於服務的生命週期限,看下面關於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()).
邦定服務是指:允許應用組件調用bindService()方法邦定一個服務,以建立長期的聯接。(並且一般不允許組件調用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 call bindService() 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()).
要創建一個邦定的服務,你必須實現onBind()回調方法,返回一個IBinder,它定義了與服務通信的接口。其他應用組件然後調用bindService()方法取回接口並….只有服務於邦到它的應用組件時,服務才存在,所以當沒有組件邦定到服務時,系統銷燬它(你不需要停止一個邦定的服務,但當服務是通過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.
要創建一個邦定的服務,首要的事情是,你必須定義與服務通信的接口。服務與客戶端之間的這個接口,必須是一個的IBinder實現,並且這就是爲什麼你的服務必須從onBind()方法中返回它的原因.
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.
多個客戶端可以同時邦定到一個服務。當某個客戶端處理完與服務的交互工作時,它可以調用unbindService()鬆邦.一旦沒有客戶端邦定到該服務,系統就銷燬該服務.
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.
有許多方法去實現邦定服務,並且它有實現比啓動服務複雜得多,所以單獨在Bound Services中討論邦定服務的。
Sending Notifications to the User發送通知給用戶
Once running, a service can notify the user of events using Toast Notifications or Status Bar Notifications.
當運行時,一個服務可以用Toast Notifications 或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).
吐司通知(彈出的窗口像吐司麪包)是一個出現在當前窗口表面的一個消息,顯示一會兒然後消失,而狀態條消息提一個帶有消息的icon顯示在狀態條上,用戶可以選擇它,執行一個動作(比如啓動一個活動)
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 Notifications developer guides for more information.
詳細信息,請看Toast Notifications 或者 Status Bar Notifications開發指南
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.
一個前臺服務是用戶通過綜合考慮後特別關心的一個服務,並且在缺少內存時,不是系統要殺掉的候選者。一個前臺服務必須爲狀態條提供一個通知,放在"Ongoing"頭下,這個意思是這個通知不能被扔掉,除非服務被停止或者被移到後臺.
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:
要請求你的服務運行到前臺,調用startForeground().方法。這個方法帶兩個參數:一個標識通知器的整數及狀態條的Notification通知器.例如:
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.
要把該服務從前臺移除,調用stopForeground()方法.這個方法帶有一個boolean值,表示是否同時將通知也從狀態條上移除。這個方法不停止服務。但是,如果你停止一個在前臺正在運行的服務,那麼該通知將也被移除.
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.
注意:startForeground()和stopForeground()這個兩方法是在Android 2.0中介紹進來的。爲了讓你的服務可以舊版本的平臺上運行,你必須使用以前的setForeground()方法。關於向後兼容請看startForeground()文檔.
For more information about notifications, see Creating Status Bar Notifications.
關於創建通知器,請看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..
該服務是其他組件調用startService()方法創建的。然後服務無限運行並且必須自己調用stopSelf()方法停止自己。其他組也可以調用stopService()方法停止它.當服務停止,系統銷燬它..
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 calling unbindService(). 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.)
該服務是其他組件調用bindService()方法開啓的.客戶端然後通過IBinder接口與服務通信,客戶端可以調用unbindService()方法斷開聯接。多個客戶端可以邦定到同一個服務並且當所有的客戶端鬆邦後,系統銷燬該服務(服務不需要自己停止自己)
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.
這兩種方法並不是完全分開的。你可以邦定一個服務到一個用startService()方法開啓的服務.比如,通過調用一個帶有指定播放音樂的Intent意圖的startService()方法,開啓一個後臺音樂播放服務.後來,用戶可能想要對播放器做一些控制或者想獲取關於當前音樂的信息,一個活動可以調用bindService()方法邦定到該服務.在像這樣的情況下,stopService()或者stopSelf()方法不能真正停止服務,除非所有的客戶端解除邦定.
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 are not required to call the superclass implementation of these callback methods.不像活動的生命週期的回調方法,你不必要去調用超類的這些回調方法的實現
Figure 2. The service lifecycle. The diagram on the left shows the lifecycle when the service is created with startService() and the diagram on the right shows the lifecycle when the service is created with bindService().
圖2.服務的生命週期,圖的左邊演示的是用startService()方法創建的服務的生命週期,圖的右邊演示的是用bindService()方法創建的服務的生命週期.
By implementing these methods, you can monitor two nested loops of the service's lifecycle:
通過實現這些方法,你可以監視到服務的生命週期的兩個嵌套循環:
The entire lifetime of a service happens between the time onCreate() is called and the time onDestroy() returns. Like an activity, a service does its initial setup in onCreate() and releases all remaining resources in onDestroy(). For example, a music playback service could create the thread where the music will be played in onCreate(), then stop the thread in onDestroy().
The onCreate() and onDestroy() methods are called for all services, whether they're created by startService() or bindService().
服務的整個的生命時間,發生在onCreate()方法被調用時和onDestroy()方法返回時.與活動一樣,服務在onCreate()方法中執行初始化操作,並在onDestroy()方法中釋放保持的資源.比如,音樂回放服務可能在onCreate()方法中創建播放音樂線程,並在onDestroy()方法中停止線程.無論它們由startService() 或者bindService()創建,所有服務都會調用onCreate()和onDestroy()方法.
The active lifetime of a service begins with a call to either onStartCommand() or onBind(). Each method is handed the Intent that was passed to either startService() or bindService(), respectively.
服務的激活生命時間,開始於對onStartCommand()方法或onBind()方法的調用.每個方法相應的處理傳給startService()方法或者bindService()方法的Intent意圖.
If the service is started, the active lifetime ends the same time that the entire lifetime ends (the service is still active even after onStartCommand() returns). If the service is bound, the active lifetime ends when onUnbind() returns.
如果服務是開啓的,該激活生命時間的結束時間同整個生命時間一樣(即使onStartCommand()方法返回了,服務仍然是激活的)。如果服務是結束邦定的,激活的生命時間結束於onUnbind()方法返回.
Note: Although a started service is stopped by a call to either stopSelf() or stopService(), there is not a respective callback for the service (there's no onStop() callback). So, unless the service is bound to a client, the system destroys it when the service is stopped—onDestroy() is the only callback received.
注意:雖然一個開啓的服務可能通過調用stopSelf()或者stopService()方法停止,但服務沒有與此相應的回調方法(沒有onStop()回調)。除非服務邦定到一個客戶端,否則當服務停止時系統就銷燬它—onDestroy() 方法是唯一回調接收方法.
Figure 2 illustrates the typical callback methods for a service. Although the figure separates services that are created by startService() from those created by bindService(), keep in mind that any service, no matter how it's started, can potentially allow clients to bind to it. So, a service that was initially started with onStartCommand() (by a client calling startService()) can still receive a call to onBind() (when a client calls bindService()).
圖2說明了一個服務的典型回調方法,雖然該圖把服務以由方法創建startService() 的和由bindService()方法創建的分開了,但請記住,不管服務是如何創建的,都能允許客戶端邦定到它。所以,用onStartCommand()方法初始化的服務(客戶端調用startService()),仍能接收一個onBind()方法的調用。
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 about Managing the Lifecycle of a Bound Service.
關於創建提供邦定的服務的詳細信息,看Bound Services文檔,在那裏的Managing the Lifecycle of a Bound Service一節,有更多關於onRebind() 回調方法的更詳細信息.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章