日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

使用IntentService在Service中创建耗时任务

發(fā)布時(shí)間:2025/3/20 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 使用IntentService在Service中创建耗时任务 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

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)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。