編輯:關於Android編程
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是一個沒有用戶界面在後台長期運行的組件,其他組件可以啟動(start)Service同時即使用戶切換到其他應用Service也可以在後台運行。另外,一個組件可以綁定(bind)Service與之交互,甚至執行跨進程通信(IPC).例如,Service可以從後台執行網絡任務、播放音樂、執行IO操作等,或者也可以和上下文提供者(activitty/services等)交互
A service can essentially take two forms:
Started A service is started when an application component (such as an activity) starts it by callingstartService()
. 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.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.
/**譯文**/
Service 本質上來講采用兩種方式(運行)
Started
當一個應用程序組件(例如一個Activity)通過調用startService()啟動Service時,service將會通過 started”方式啟動。一旦啟動,即使啟動Service的應用程序組件被銷毀,Service也會在後台持續運行。通常,一個通過started方式啟動的service 執行 一個單一的操作並且不會返回結果給調用者(啟動者)。例如,它(Service)可以通過網絡上傳或者下載文件。當執行的操作結束的時候。Service會自動終止。
Bound
當一個應用程序組件(例如一個Activity)通過調用bindService()啟動Service時,service將會通過 bound”方式啟動。一個綁定的Service甚至可以在跨進程通信的情形下通過提供發送request 獲取result的客戶端—服務器式的接口允許組件與之通信。bound Service只有在其他應用程序組件綁定它的時候才會運行。多個組件可以同時綁定Service,但是只有在所有的組件解除綁定之後,service 才會銷毀。
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.
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 anIntent
. 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 aboutDeclaring the service in the manifest.
Caution: A service runs in the main thread of its hosting process—the service doesnot create its own thread and doesnot 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.
/**譯文**/
縱使上文總體上來講分別討論Service兩種方式,Service可以同時通過兩種方式運行實現,他即可以直接運行(started)也可以綁定(bound).而這也只是執行onStartCommand()允許組件started或者onBind()綁定來會回調的問題。
不管你的應用程序(Service)started 還是Bound或是兩者啟動,任何組件可以使用這個服務(甚至是其他應用)。好比,任何組件可以通過Intent啟動activity。然而,你可以把自己的service申明為私有,並在manifest 文件鎖住其他應用的使用權限。更多查看Declaring the service in the manifest.
注意:Service只能運行在它的宿主進程的主進程,它不能創造自己的進程或者運行在一個單獨的進程(除非你指定)。這就意味著。如果你的Service要執行任何耗CPU的任務或者阻塞的操作,你應該另起一個包含Service的進程去執行它。通過使用單獨進程,你可以減少應用程序未響應或者錯誤的風險。同時應用程序的主線程可以繼續致力於與用戶交互活動。
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.
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 inonStop()
. Also consider usingAsyncTask
orHandlerThread
, instead of the traditionalThread
class. See theProcesses and Threading document for more information about threads.
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.
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 是一個即使用戶不在與應用程序交互時也在後台運行的基本組件。因此,如果這是你需要的你可以創建自己的服務(Service)
如果你需要執行一個主線程之外的操作但他只是在用戶與你的應用程序交互的情況下,那麼。毫無疑問,你需要的只是一個新的線程而不是一個服務。例如,如果你想只在activity運行的時候播放一些音樂。那麼你只需要在activity的onCreate()創建一個線程,在onStart()中啟動它, 然後在onStop()
停止它, 當然你也可以考慮使用AsyncTask 或者HandlerThread替代傳統的Thread.在Processes and Threading查看更多
記住,如果你確定需要使用服務,它默認情況下運行在您的應用程序的主線程,所以你在執行密集或阻塞的操作時還是應該要在服務內創建一個新線程。
創建一個服務,您必須創建服務類(或它的一個現有的子類)。在你的實現過程中,你需要重寫一些處理的服務生命周期的關鍵方面和提供綁定服務於組件的回調方法,如果合適的話。你應該忽略最重要的回調方法:
onStartCommand()
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 callingstopSelf()
orstopService()
. (If you only want to provide binding, you don't need to implement this method.) 當其他組件(如Activity)通過調用startService()啟動Service時,系統會自動調用該方法(onStartCommand()
)。一旦這個方法被執行,Service會自動在後台運行。如果你實現了該方法。你就要記得在任務完成時調用stopSelf() orstopService()停止Service。(如果你只想提供綁定就不需要實現該方法)
onBind()
The system calls this method when another component wants to bind with the service (such as to perform RPC), by callingbindService()
. In your implementation of this method, you must provide an interface that clients use to communicate with the service, by returning anIBinder
. You must always implement this method, but if you don't want to allow binding, then you should return null. 當其他組件想通過調用bindService()綁定服務去執行比如RPC的服務時,系統會自動調用該方法。在你是實現該方法時,你必須提供一個返回IBinder的,客戶端能夠與Service交互的接口。如果你不允許綁定,你可以 return nullonCreate()
The system calls this method when the service is first created, to perform one-time setup procedures (before it calls eitheronStartCommand()
oronBind()
). If the service is already running, this method is not called. 當服務第一次創建的時候系統會自動調用該方法去執行一系列建立Service操作(它一定會在onStartCommand() oronBind()
).前調用)。如果你的Service已經在運行。這個方法不會被調用。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.當Service不再使用或者被銷毀時系統會自動調用該方法。你的服務應該實現這個去清理如線程,注冊的監聽器,接收器,等資源。這是最後一次調用服務接收。
If a component starts the service by callingstartService()
(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())啟動Service,Service將會一直運行直到他自己調用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 theProcesses and Threading document.
當系統可用內存不足的時候,Android系統將會強行停止Service為回復用戶聚焦的核心Activity需要的資源。如果你的Service被綁定到用戶聚焦的Activity,Service將很少幾率被殺掉,如果你的Service被申明run in the foreground(稍後討論),那麼他將幾乎不能可能被殺掉。相應的,如果Service啟動了並且長期運行,那麼隨著時間推移,系統會自動降低他在後台任務隊列中的地位,那麼它將極有可能被殺掉。如果你的服務極有可能被殺掉,那麼你應該巧妙的設計讓它能夠被系統重新啟動。如果系統最終還是殺掉了你的service,那麼在資源可用(同樣,者就取決於你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.
下面就告訴你如何創建不同的service和從其他應用組件如何使用它
Like activities (and other components), you must declare all services in your application's manifest file.
To declare your service, add a
element as a child of the element. For example:
... ...
See the
element reference for more information about declaring your service in the manifest.
There are other attributes you can include in the
element to define properties such as permissions required to start the service and the process in which the service should run. Theandroid: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 risk breaking code due to dependence on explicit intents to start or bind the service (read the blog post, Things That Cannot Change).
To ensure your app is secure, always use an explicit intent when starting or binding yourService
and do not declare intent filters for the service. If it's critical that you allow for some amount of ambiguity as to which service starts, you can supply intent filters for your services and exclude the component name from theIntent
, but you then must set the package for the intent withsetPackage()
, which provides sufficient disambiguation for the target service.
Additionally, you can ensure that your service is available to only your app by including theandroid:exported
attribute and setting it to false
. This effectively stops other apps from starting your service, even when using an explicit intent.
中可以包含一些啟動服務所需的權限和服務應該運行在的進程的屬性 。
android:name
是唯一一個必須的屬性。它指定了服務的類名稱。一旦你發布你的應用,你不能改變這個名稱,因為如果你做,你可能打破代碼由於對啟動或綁定服務的依賴的Intent(閱讀博客文章,Things That Cannot Change)。
為了確保你的應用是安全的,記住用明確的Intent去啟動或者綁定你的Service,並且不要使用啟動service的intent filters。如果你必須允許一定量的模糊性去啟動服務,您可以為您的服務提供intent filters 和排除component name的Intent,但同時你也必須為你的intent用 setPackage() 設置能夠消除歧義的包名。
同時,你可是設置android:exported
=false去確保你的Service只對你的app可用,這有效地停止從其他應用程序啟動你的服務,甚至使用一個明確的Intent時
A started service is one that another component starts by calling startService()
, resulting in a call to the service's onStartCommand()
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 callingstopService()
.
An application component such as an activity can start the service by calling startService()
and passing anIntent
that specifies the service and includes any data for the service to use. The service receives thisIntent
in theonStartCommand()
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 tostartService()
. 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 implementonHandleIntent()
, which receives the intent for each start request so you can do the background work.
started service是通過調用startService()執行service'sonStartCommand()的方法一類組件
當一個service 通過started啟動,它的生命周期獨立於啟動他的組件,縱使啟動它的組件被銷毀,它也可以在後台運行,正因為如此,終止服務需要自己調用stopSelf()或者其他組件調用stopService()
好比activity的組件可以調用startService()啟動Service並傳遞一個intent指定服務並包含全部服務使用的數據,Service在onStartCommand()接收Intent
例如,假設一個Activity需要保存一些數據到網絡數據庫。Activity可以啟動一個服務通過一個Intent啟動startService()傳遞數據去保存,服務在onstartcommand()接收Intent,連接到互聯網並執行數據庫事務。當交易完成後,該服務停止並摧毀。
注意: Service 默認情況下運行在它所在的應用的主線程,如果你的服務執行密集或阻塞的操作而用戶又在於應用程序交互,那麼service將拖慢你的程序效率,為了提高你的用戶體驗,你應該在Service內擰起一個線程
The following sections describe how you can implement your service using either one for these classes.
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 theIntentService
class.
由於大多數的started Service 不需要處理多路請求(實際上是一個多線程的危險的情況下),你最好還是使用IntentService
The IntentService
does the following:
onStartCommand()
separate from your application's main thread. 創建一個默認的工作線程去把Intent傳遞給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. 創建一個工作隊列去初次傳遞你的Intent給你實現的onHandleIntent()從而讓你不用擔心多線程的情況Stops the service after all start requests have been handled, so you never have to callstopSelf()
.在處理完所有的request被處理後自動終止Service,你不需要調用stopSelf().Provides default implementation of onBind()
that returns null. 提供默認返回null的onBind()實現Provides a default implementation of onStartCommand()
that sends the intent to the work queue and then to your onHandleIntent()
implementation. 提供默認的onStartCommand()傳遞Intent到工作隊列和你實現的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() < 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()
, oronDestroy()
, be sure to call the super implementation, so that theIntentService
can properly handle the life of the worker thread.
記得重寫onCreate()
,onStartCommand()
, oronDestroy()一定要super. 從而IntentService可以自動處理
For example, onStartCommand()
must return the default implementation (which is how the intent gets delivered toonHandleIntent()
):
@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 baseService
class, which is a lot more code, but which might be appropriate if you need to handle simultaneous start requests.
//今天先翻譯到這把,下次有時間補完它
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 theService
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 forIntentService
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.
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
. (You should never callonStartCommand()
directly.)
For example, an activity can start the example service in the previous section (HelloSevice
) using an explicit intent withstartService()
:
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 aPendingIntent
for a broadcast (withgetBroadcast()
) 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()
orstopService()
) is required to stop it.
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 afteronStartCommand()
returns. So, the service must stop itself by calling stopSelf()
or another component can stop it by callingstopService()
.
Once requested to stop with stopSelf()
orstopService()
, 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 callstopSelf(int)
, you pass the ID of the start request (thestartId
delivered to onStartCommand()
) to which your stop request corresponds. Then if the service received a new start request before you were able to callstopSelf(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 callingstopService()
. Even if you enable binding for the service, you must always stop the service yourself if it ever received a call toonStartCommand()
.
For more information about the lifecycle of a service, see the section below aboutManaging the Lifecycle of a Service.
A bound service is one that allows application components to bind to it by callingbindService()
in order to create a long-standing connection (and generally does not allow components tostart it by callingstartService()
).
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 donot need to stop a bound service in the way you must when the service is started throughonStartCommand()
).
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 ofIBinder
and is what your service must return from theonBind()
callback method. Once the client receives theIBinder
, 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 callsunbindService()
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 aboutBound Services.
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 Notifications developer guides for more information.
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 theNotification
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_ID, notification);
Caution: The integer ID you give to startForeground()
must not be 0.
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 doesnot stop the service. However, if you stop the service while it's still running in the foreground, then the notification is also removed.
For more information about notifications, see Creating Status Bar Notifications.
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 serviceThe 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..
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 doesnot need to stop itself.)
These two paths are not entirely separate. That is, you can bind to a service that was already started withstartService()
. 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 callingbindService()
. In cases like this, stopService()
orstopSelf()
does not actually stop the service until all clients unbind.
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 voidonCreate
() { // The service is being created } @Override public intonStartCommand
(Intent intent, int flags, int startId) { // The service is starting, due to a call tostartService()
return mStartMode; } @Override public IBinderonBind
(Intent intent) { // A client is binding to the service withbindService()
return mBinder; } @Override public booleanonUnbind
(Intent intent) { // All clients have unbound withunbindService()
return mAllowRebind; } @Override public voidonRebind
(Intent intent) { // A client is binding to the service withbindService()
, // after onUnbind() has already been called } @Override public voidonDestroy
() { // 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.
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 timeonDestroy()
returns. Like an activity, a service does its initial setup inonCreate()
and releases all remaining resources inonDestroy()
. For example, a music playback service could create the thread where the music will be played inonCreate()
, then stop the thread inonDestroy()
.
The onCreate()
andonDestroy()
methods are called for all services, whether they're created bystartService()
orbindService()
.
onStartCommand()
oronBind()
. Each method is handed theIntent
that was passed to eitherstartService()
orbindService()
, respectively.
If the service is started, the active lifetime ends the same time that the entire lifetime ends (the service is still active even afteronStartCommand()
returns). If the service is bound, the active lifetime ends when onUnbind()
returns.
Note: Although a started service is stopped by a call to eitherstopSelf()
orstopService()
, 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.
Figure 2 illustrates the typical callback methods for a service. Although the figure separates services that are created bystartService()
from those created bybindService()
, 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 withonStartCommand()
(by a client callingstartService()
) can still receive a call toonBind()
(when a client callsbindService()
).
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.
伴隨著“Dalvik is dead,long live Dalvik“這行AOSP代碼提交日志,在Android5.0中,ART運行時取代了Da
公司項目需求,需要給軟件加入報警功能, 點擊手繪的報警圖標,開始震動,並且發出報警鈴音, 使用了layerlist,drawable,Vibrator,soundpool
AlertDialog生成的對話框可分為4個區域:圖標區,標題區,內容區,按鈕區結構如圖:AlertDialog對話框的使用:1,創建AlertDialog.Builde
Intent: 官方解釋: An intent is an abstract description of an operation to be performed. I