為什么會有IntentService?
我們知道,Service作為四大組件之一,也會是運行在主線程的,所以我們?nèi)绻泻臅r的操作,應(yīng)該新開一個線程。
為此android專門提供了一個類,就是IntentService,它的里邊包含了一個handler用于處理后臺線程。
使用IntentService,首先繼承它,然后實現(xiàn)onHandleIntent()方法。
舉個例子,模擬上傳和下載文件的demo:
我的IntentService:
package example.ylh.com.service_demo;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
/**
* Created by yangLiHai on 2017/8/30.
*/
public class TestIntentService extends IntentService {
private String TAG = TestIntentService.class.getSimpleName();
public static final String ACTION_UPLOAD_FILE = "action_upload_file";
public static final String ACTION_DOWNLOAD_FILE = "action_download_file";
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* Used to name the worker thread, important only for debugging.
*/
public TestIntentService() {
super("test intent service");
Log.e(TAG,"construction");
}
@Override
public void onCreate() {
Log.e(TAG,"oncreate");
super.onCreate();
}
@Override
public void onDestroy() {
Log.e(TAG,"ondestroy");
super.onDestroy();
}
@Override
protected void onHandleIntent(Intent intent) {
String action = intent.getAction();
if (action.equals(ACTION_DOWNLOAD_FILE)){
downloadFile();
}else if (action.equals(ACTION_UPLOAD_FILE)){
uploadFile();
}
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void uploadFile(){
Log.e(TAG,"handleintent upload:"+Thread.currentThread().getId()+"");
}
private void downloadFile(){
Log.e(TAG,"handleintent download:"+Thread.currentThread().getId()+"");
}
}
activity代碼:
package example.ylh.com.service_demo;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import example.ylh.com.R;
/**
* Created by yanglihai on 2017/8/17.
*/
public class ServiceTestActivity extends Activity {
public static final String TAG = ServiceTestActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.service_test_activity);
findViewById(R.id.btn4).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startUploadService();
}
});
findViewById(R.id.btn5).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startDownloadService();
}
});
}
public void startDownloadService(){
Intent i = new Intent(ServiceTestActivity.this, TestIntentService.class);
i.setAction(TestIntentService.ACTION_DOWNLOAD_FILE);
startService(i);
}
public void startUploadService(){
Intent i = new Intent(ServiceTestActivity.this, TestIntentService.class);
i.setAction(TestIntentService.ACTION_UPLOAD_FILE);
startService(i);
}
}
通過Intent來傳遞數(shù)據(jù),分發(fā)不同的任務(wù)。多次調(diào)用會被內(nèi)部的handler放到隊列中,任意時間只有一個intent正在被處理,隊列中沒有需要處理的任務(wù)的時候,就會銷毀自己。
多次點擊兩個按鈕的打印結(jié)果如下:
可以清楚地看到,上傳和下載任務(wù)都是在子線程中執(zhí)行的,當(dāng)所有的任務(wù)執(zhí)行完之后就會destroy。所以使用IntentService我們不用考慮Service的生命周期,也不用自己創(chuàng)建子線程開啟任務(wù),一切都幫我們做好了,用起來還是很方便的。
IntentService源碼解析
IntentService繼承自Service,他是一個特殊的service,它的內(nèi)部封裝了HandlerThread和Handler。
這是它的onCreate方法:
@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);
}
第一次啟動的時候,onCreate方法會被調(diào)用,創(chuàng)建了一個HandlerThread,然后使用它的looper來構(gòu)造mServiceHandler(一個handler對象)。這樣mServiceHandler就可以在子線程處理任務(wù)了。執(zhí)行完oncreat之后,就會執(zhí)行onStartCommand方法,多次啟動IntentService就會多次調(diào)用onStartCommand方法,
這是onStartCommand方法的具體代碼:
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
可以看見里邊調(diào)用了onStart方法,我們再來看看onStart方法:
@Override
public void onStart(@Nullable Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
在onStart方法中,每次都會用mServiceHandler發(fā)送一個消息,然后我們在看看mServiceHandler的代碼:
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);
}
}
可以清楚地看到,每次收到intent之后,都會把intent交給onHandleIntent方法去處理,也就是我們需要重寫的方法,通過intent我們可以解析出來外界傳進(jìn)來的數(shù)據(jù),做相應(yīng)的處理。onHandleIntent執(zhí)行完之后,又執(zhí)行了stopSelf(int startid)方法去關(guān)閉自身。但是他不是立刻去關(guān)閉,而是等待所有的intent被處理完之后才終止服務(wù)。一般來說,stopSelf(int startId)在關(guān)閉之前都會判斷最近啟動服務(wù)的次數(shù)和startId是否相等,如果相等就立刻停止服務(wù),如果不相等,則不停止。
IntentService多數(shù)情況下都非常簡單實用,你只需要生成后臺任務(wù)操作,而不用關(guān)系啟動時機(jī),如果給IntentService發(fā)送多個Intent,這些Intent會按順序執(zhí)行,每次執(zhí)行一個。如果有并發(fā)需求,并不適合用IntentService,還是自己寫Service吧。
IntentService到這里已經(jīng)說完了,看完我的例子在看看源碼,相信你已經(jīng)能完全理解了。
如果那里說的不夠準(zhǔn)確請給我留言,謝謝。