IntentService如何在Android項目中使用 ?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。
創(chuàng)新互聯(lián)專注于陸港企業(yè)網(wǎng)站建設(shè),成都響應(yīng)式網(wǎng)站建設(shè)公司,電子商務(wù)商城網(wǎng)站建設(shè)。陸港網(wǎng)站建設(shè)公司,為陸港等地區(qū)提供建站服務(wù)。全流程按需求定制制作,專業(yè)設(shè)計,全程項目跟蹤,創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務(wù)
Android IntentService詳解
一、IntentService簡介
IntentService是Service的子類,比普通的Service增加了額外的功能。先看Service本身存在兩個問題:
二、IntentService特征
三、使用步驟(詳情參考Service項目)
繼承IntentService類,并重寫onHandleIntent()方法即可;
MainActivity.Java文件
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void startService(View source) { // 創(chuàng)建所需要啟動的Service的Intent Intent intent = new Intent(this, MyService.class); startService(intent); } public void startIntentService(View source) { // 創(chuàng)建需要啟動的IntentService的Intent Intent intent = new Intent(this, MyIntentService.class); startService(intent); } }
MyIntentService.java文件
public class MyIntentService extends IntentService { public MyIntentService() { super("MyIntentService"); } @Override protected void onHandleIntent(Intent intent) { // IntentService會使用單獨的線程來執(zhí)行該方法的代碼 // 該方法內(nèi)執(zhí)行耗時任務(wù),比如下載文件,此處只是讓線程等待20秒 long endTime = System.currentTimeMillis() + 20 * 1000; System.out.println("onStart"); while (System.currentTimeMillis() < endTime) { synchronized (this) { try { wait(endTime - System.currentTimeMillis()); } catch (InterruptedException e) { e.printStackTrace(); } } } System.out.println("----耗時任務(wù)執(zhí)行完成---"); } }
MyService.java文件
public class MyService extends Service { @Override public IBinder onBind(Intent arg0) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { // 該方法內(nèi)執(zhí)行耗時任務(wù)可能導(dǎo)致ANR(Application Not Responding)異常 long endTime = System.currentTimeMillis() + 20 * 1000; System.out.println("onStart"); while (System.currentTimeMillis() < endTime) { synchronized (this) { try { wait(endTime - System.currentTimeMillis()); } catch (InterruptedException e) { e.printStackTrace(); } } } System.out.println("----耗時任務(wù)執(zhí)行完成---"); return START_STICKY; } }
看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進(jìn)一步的了解或閱讀更多相關(guān)文章,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對創(chuàng)新互聯(lián)的支持。
網(wǎng)站題目:IntentService如何在Android項目中使用
轉(zhuǎn)載注明:http://muchs.cn/article0/iepeio.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站內(nèi)鏈、軟件開發(fā)、云服務(wù)器、網(wǎng)頁設(shè)計公司、靜態(tài)網(wǎng)站、做網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)