使用IntentService在Service中创建耗时任务
IntentService是Service的子類,比普通的Service增加了額外的功能。
Service存在兩個(gè)問(wèn)題:
1,Service不會(huì)專門(mén)啟動(dòng)一條單獨(dú)的線程,Service與它所在應(yīng)用訪問(wèn)者位于同一條線程
2,Service也不是專門(mén)一條新線程,因此不應(yīng)該在Service中直接處理耗時(shí)任務(wù)
IntentService的特點(diǎn):
1,IntentService將會(huì)使用隊(duì)列來(lái)管理請(qǐng)求Intent,每當(dāng)客戶端代碼通過(guò)In疼痛與請(qǐng)求啟動(dòng)IntentService時(shí),IntentService會(huì)將Intent加入隊(duì)列,然后啟動(dòng)一條新的worker線程來(lái)處理該Intent。
2,IntentService使用新的worker線程處理intent請(qǐng)求,因此不會(huì)阻塞主線程。
3,IntentService會(huì)創(chuàng)建單獨(dú)的worker線程來(lái)處理onHandleIntent()方法實(shí)現(xiàn)的代碼
4,所有請(qǐng)求處理完成后,IntentService會(huì)自動(dòng)停止,不用調(diào)用stopSelf方法來(lái)停止Service
5,為Service的onBind()方法提供了默認(rèn)實(shí)現(xiàn),默認(rèn)實(shí)現(xiàn)的onBind()方法返回null
6,為Service的onStarCommand()方法提供的默認(rèn)實(shí)現(xiàn),會(huì)把請(qǐng)求Intent添加到隊(duì)列中
在Service中執(zhí)行耗時(shí)任務(wù)的方法:
A,使用普通Service,在OnCreate中創(chuàng)建線程
B,使用IntentService,重寫(xiě)onHandleIntent()方法創(chuàng)建耗時(shí)任務(wù)
使用IntentService時(shí),只需要繼承IntentService,重寫(xiě)onHandleIntent()就行了
IntentServiceTest.java
public class IntentServiceTest extends Activity {@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);}public void startIntentService(View source){// 創(chuàng)建需要啟動(dòng)的IntentService的IntentIntent intent = new Intent(this, MyIntentService.class);// 啟動(dòng)IntentServicestartService(intent);} } MyIntentService.java
public class MyIntentService extends IntentService//繼承IntentService {public MyIntentService(){super("MyIntentService");}// IntentService會(huì)使用單獨(dú)的線程來(lái)執(zhí)行該方法的代碼@Overrideprotected void onHandleIntent(Intent intent){// 該方法內(nèi)可以執(zhí)行任何耗時(shí)任務(wù),比如下載文件等,此處只是讓線程暫停20秒long endTime = System.currentTimeMillis() + 20 * 1000;System.out.println("onStart");while (System.currentTimeMillis() < endTime){synchronized (this){try{wait(endTime - System.currentTimeMillis());}catch (Exception e){}}}System.out.println("---耗時(shí)任務(wù)執(zhí)行完成---");} }
總結(jié)
以上是生活随笔為你收集整理的使用IntentService在Service中创建耗时任务的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Android中的Service组件详解
- 下一篇: Http中的Post和GET请求的区别