一救军、Service的介紹
Service的官方介紹中比較重要的兩點:
1.A Service is not a separate process. The Service object itself does
not imply it is running in its own process; unless otherwise specified,
it runs in the same process as the application it is part of.
2.A Service is not a thread. It is not a means itself to do work off
of the main thread (to avoid Application Not Responding errors).
簡單翻譯一下
1.Service不是一個單獨的進程 财异,服務對象本身并不意味著它運行在自己的進程倘零,除非另有規(guī)定唱遭,它運行在同一進程中作為應用程序的一部分。
2.Service不是一個線程呈驶,所以我們應該避免在Service里面進行耗時的操作拷泽。
重點注意:Service不是一個線程,不能直接處理耗時的操作袖瞻。
二司致、IntentService的用法
簡單說,IntentService是繼承于Service并處理異步請求的一個類聋迎,在IntentService內(nèi)有一個工作線程來處理耗時操作脂矫,啟動IntentService的方式和啟動傳統(tǒng)Service一樣,同時霉晕,當任務執(zhí)行完后庭再,IntentService會自動停止,而不需要我們?nèi)ナ謩涌刂莆摺A硗庵羟幔梢詥覫ntentService多次,而每一個耗時操作會以工作隊列的方式在IntentService的onHandleIntent回調(diào)方法中執(zhí)行伟葫,并且恨搓,每次只會執(zhí)行一個工作線程,執(zhí)行完第一個再執(zhí)行第二個,以此類推斧抱。
而且常拓,所有請求都在一個單線程中,不會阻塞應用程序的主線程(UI Thread)辉浦,同一時間只處理一個請求墩邀。
那么,用IntentService有什么好處呢盏浙?首先眉睹,我們省去了在Service中手動開線程的麻煩,第二废膘,當操作完成時竹海,我們不用手動停止Service。
IntentService的源碼
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);
}
}
@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(Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
這就是IntentService丐黄,一個方便我們處理業(yè)務流程的類斋配,它是一個Service,但是比Service更智能灌闺。
三艰争、Thread和Service的區(qū)別
Thread:Thread 是程序執(zhí)行的最小單元,它是分配CPU的基本單位桂对∷ψ浚可以用 Thread 來執(zhí)行一些異步的操作。
Service:Service 是android的一種機制蕉斜,當它運行的時候如果是Local Service逾柿,那么對應的Service 是運行在主進程的 main 線程上的。如:onCreate宅此,onStart 這些函數(shù)在被系統(tǒng)調(diào)用的時候都是在主進程的 main 線程上運行的机错。如果是Remote Service,那么對應的 Service 則是運行在獨立進程的 main 線程上父腕。
那么為什么我們不直接用Thread而要用Service呢弱匪?其實這跟 android 的系統(tǒng)機制有關,我們先拿Thread 來說璧亮。Thread 的運行是獨立于 Activity 的萧诫,也就是說當一個 Activity 被 finish 之后,如果你沒有主動停止 Thread 或者 Thread 里的 run 方法沒有執(zhí)行完畢的話杜顺,Thread 也會一直執(zhí)行财搁。因此這里會出現(xiàn)一個問題:當 Activity 被 finish 之后,你不再持有該 Thread 的引用躬络。另一方面尖奔,你沒有辦法在不同的 Activity 中對同一 Thread 進行控制。
Thread和Service的使用場景:
1、在應用中提茁,如果是長時間的在后臺運行淹禾,而且不需要交互的情況下,使用服務茴扁。同樣是在后臺運行铃岔,不需要交互的情況下,如果只是完成某個任務峭火,之后就不需要運行毁习,而且可能是多個任務,需要長時間運行的情況下使用線程卖丸。
2纺且、如果任務占用CPU時間多,資源大的情況下稍浆,要使用線程载碌。