服務(wù)(Service)是Android中實(shí)現(xiàn)程序后臺(tái)運(yùn)行的解決方案,它的運(yùn)行不依賴于任何用戶界面,適合去執(zhí)行那些不需要和用戶交互且需要長期運(yùn)行的任務(wù)。
注意
- Service并不是運(yùn)行在一個(gè)獨(dú)立的進(jìn)程中,而是依賴于創(chuàng)建服務(wù)時(shí)所在的應(yīng)用程序進(jìn)程。當(dāng)某個(gè)應(yīng)用程序進(jìn)程被殺掉時(shí),所有依賴于該進(jìn)程的服務(wù)也會(huì)停止運(yùn)行。
- 服務(wù)并不會(huì)自動(dòng)開啟線程,所有的代碼都默認(rèn)運(yùn)行在主線程中。所以,我們需要在服務(wù)內(nèi)部手動(dòng)創(chuàng)建子線程,并在這里執(zhí)行具體的任務(wù),避免出現(xiàn)主線程阻塞的情況。
生命周期
onCreate():服務(wù)第一次創(chuàng)建的時(shí)候調(diào)用的
onStartCommand():每次啟動(dòng)服務(wù)的時(shí)候都會(huì)調(diào)用
onBind():綁定服務(wù)的時(shí)候調(diào)用
onUnBind():解綁服務(wù)的時(shí)候調(diào)用
onDestory():銷毀服務(wù)的時(shí)候調(diào)用


補(bǔ)充:
- 每個(gè)服務(wù)都只會(huì)存在一個(gè)實(shí)例,不管調(diào)用了多少次startService or bindService方法,只需要調(diào)用一次stopService(或stopSelf)or unbindService方法,服務(wù)就會(huì)停止。
- 一個(gè)服務(wù)只要被啟動(dòng)或被綁定之后,就會(huì)一直處于運(yùn)行狀態(tài),必須讓上述兩種條件同時(shí)不滿足,服務(wù)才能被銷毀。
啟動(dòng)方式對(duì)比
| 啟動(dòng)方式 | 終止方式 | 特點(diǎn) |
|---|---|---|
| startService() | 啟動(dòng)服務(wù)的控件調(diào)用stopService or 服務(wù)內(nèi)部自己調(diào)用stopSelf or 依賴的進(jìn)程銷毀 | 不需要獲取服務(wù)的數(shù)據(jù),服務(wù)不隨控件的銷毀而終止 |
| bindService() | 綁定服務(wù)的控件調(diào)用unbindService or 綁定服務(wù)的控件銷毀 or 依賴的進(jìn)程銷毀 | 需要獲取服務(wù)的數(shù)據(jù),服務(wù)隨著控件的銷毀而終止 |
注意:
- 沒有調(diào)用bindService直接調(diào)用unbindService會(huì)出現(xiàn)異常:
java.lang.IllegalArgumentException: Service not registered;
沒有調(diào)用startService直接調(diào)用stopService則沒事
服務(wù)的分類

前臺(tái)服務(wù)了解
前臺(tái)服務(wù)會(huì)一直有一個(gè)正在運(yùn)行的圖標(biāo)在系統(tǒng)的狀態(tài)欄顯示,下拉狀態(tài)欄可以看到更加詳細(xì)的信息,類似于通知的效果。使用前臺(tái)服務(wù),可以防止服務(wù)由于系統(tǒng)內(nèi)存不足等原因被回收掉,而且可以滿足一些特殊需求顯示信息。
public class MyService extends Service {
@Override
public void onCreate() {
super.onCreate();
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("this is title")
.setContentText("I'm SO HAPPY")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.smile)
.setContentIntent(pendingIntent)
.build();
startForeground((int) (Math.random() * 100), notification);
}
}
IntentService了解
IntentService是一個(gè)用于處理異步請(qǐng)求的基類,客戶端通過startService發(fā)送請(qǐng)求。該服務(wù)按需啟動(dòng),用子線程依次處理每個(gè)Intent,并且當(dāng)它執(zhí)行完成時(shí)自動(dòng)停止。內(nèi)部實(shí)現(xiàn)機(jī)制為Handler。
/**
* IntentService is a base class for {@link Service}s that handle asynchronous
* requests (expressed as {@link Intent}s) on demand. Clients send requests
* through {@link android.content.Context#startService(Intent)} calls; the
* service is started as needed, handles each Intent in turn using a worker
* thread, and stops itself when it runs out of work.
*
* <p>This "work queue processor" pattern is commonly used to offload tasks
* from an application's main thread. The IntentService class exists to
* simplify this pattern and take care of the mechanics. To use it, extend
* IntentService and implement {@link #onHandleIntent(Intent)}. IntentService
* will receive the Intents, launch a worker thread, and stop the service as
* appropriate.
*
* <p>All requests are handled on a single worker thread -- they may take as
* long as necessary (and will not block the application's main loop), but
* only one request will be processed at a time.
*
* @see android.os.AsyncTask
*/
public abstract class IntentService extends Service {
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private String mName;
private boolean mRedelivery;
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
onHandleIntent((Intent)msg.obj);
stopSelf(msg.arg1);
}
}
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public IntentService(String name) {
super();
mName = name;
}
/**
* Sets intent redelivery preferences. Usually called from the constructor
* with your preferred semantics.
*
* <p>If enabled is true,
* {@link #onStartCommand(Intent, int, int)} will return
* {@link Service#START_REDELIVER_INTENT}, so if this process dies before
* {@link #onHandleIntent(Intent)} returns, the process will be restarted
* and the intent redelivered. If multiple Intents have been sent, only
* the most recent one is guaranteed to be redelivered.
*
* <p>If enabled is false (the default),
* {@link #onStartCommand(Intent, int, int)} will return
* {@link Service#START_NOT_STICKY}, and if the process dies, the Intent
* dies along with it.
*/
public void setIntentRedelivery(boolean enabled) {
mRedelivery = enabled;
}
@Override
public void onCreate() {
// TODO: It would be nice to have an option to hold a partial wakelock
// during processing, and to have a static startService(Context, Intent)
// method that would launch the service & hand off a wakelock.
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public void onStart(@Nullable Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
/**
* You should not override this method for your IntentService. Instead,
* override {@link #onHandleIntent}, which the system calls when the IntentService
* receives a start request.
* @see android.app.Service#onStartCommand
*/
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
@Override
public void onDestroy() {
mServiceLooper.quit();
}
/**
* Unless you provide binding for your service, you don't need to implement this
* method, because the default implementation returns null.
* @see android.app.Service#onBind
*/
@Override
@Nullable
public IBinder onBind(Intent intent) {
return null;
}
/**
* This method is invoked on the worker thread with a request to process.
* Only one Intent is processed at a time, but the processing happens on a
* worker thread that runs independently from other application logic.
* So, if this code takes a long time, it will hold up other requests to
* the same IntentService, but it will not hold up anything else.
* When all requests have been handled, the IntentService stops itself,
* so you should not call {@link #stopSelf}.
*
* @param intent The value passed to {@link
* android.content.Context#startService(Intent)}.
* This may be null if the service is being restarted after
* its process has gone away; see
* {@link android.app.Service#onStartCommand}
* for details.
*/
@WorkerThread
protected abstract void onHandleIntent(@Nullable Intent intent);
}