為什么會(huì)有IntentService撑蚌?
我們知道挠说,Service作為四大組件之一吵冒,也會(huì)是運(yùn)行在主線程的纯命,所以我們?nèi)绻泻臅r(shí)的操作,應(yīng)該新開一個(gè)線程痹栖。
為此android專門提供了一個(gè)類亿汞,就是IntentService,它的里邊包含了一個(gè)handler用于處理后臺(tái)線程揪阿。
使用IntentService疗我,首先繼承它,然后實(shí)現(xiàn)onHandleIntent()方法南捂。
舉個(gè)例子吴裤,模擬上傳和下載文件的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)用會(huì)被內(nèi)部的handler放到隊(duì)列中麦牺,任意時(shí)間只有一個(gè)intent正在被處理,隊(duì)列中沒有需要處理的任務(wù)的時(shí)候鞭缭,就會(huì)銷毀自己剖膳。
多次點(diǎn)擊兩個(gè)按鈕的打印結(jié)果如下:
可以清楚地看到,上傳和下載任務(wù)都是在子線程中執(zhí)行的岭辣,當(dāng)所有的任務(wù)執(zhí)行完之后就會(huì)destroy吱晒。所以使用IntentService我們不用考慮Service的生命周期,也不用自己創(chuàng)建子線程開啟任務(wù)沦童,一切都幫我們做好了仑濒,用起來還是很方便的。
IntentService源碼解析
IntentService繼承自Service偷遗,他是一個(gè)特殊的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);
}
第一次啟動(dòng)的時(shí)候鹦肿,onCreate方法會(huì)被調(diào)用矗烛,創(chuàng)建了一個(gè)HandlerThread,然后使用它的looper來構(gòu)造mServiceHandler(一個(gè)handler對象)箩溃。這樣mServiceHandler就可以在子線程處理任務(wù)了瞭吃。執(zhí)行完oncreat之后,就會(huì)執(zhí)行onStartCommand方法涣旨,多次啟動(dòng)IntentService就會(huì)多次調(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方法中霹陡,每次都會(huì)用mServiceHandler發(fā)送一個(gè)消息和蚪,然后我們在看看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之后,都會(huì)把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)閉之前都會(huì)判斷最近啟動(dòng)服務(wù)的次數(shù)和startId是否相等速妖,如果相等就立刻停止服務(wù)高蜂,如果不相等,則不停止罕容。
IntentService多數(shù)情況下都非常簡單實(shí)用备恤,你只需要生成后臺(tái)任務(wù)操作,而不用關(guān)系啟動(dòng)時(shí)機(jī)杀赢,如果給IntentService發(fā)送多個(gè)Intent烘跺,這些Intent會(huì)按順序執(zhí)行,每次執(zhí)行一個(gè)脂崔。如果有并發(fā)需求,并不適合用IntentService梧喷,還是自己寫Service吧砌左。
IntentService到這里已經(jīng)說完了,看完我的例子在看看源碼铺敌,相信你已經(jīng)能完全理解了汇歹。
如果那里說的不夠準(zhǔn)確請給我留言,謝謝偿凭。