W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
編寫:kesenhoo - 原文:http://developer.android.com/training/run-background-service/create-service.html
IntentService為在單一后臺線程中執(zhí)行任務(wù)提供了一種直接的實現(xiàn)方式。它可以處理一個耗時的任務(wù)并確保不影響到UI的響應(yīng)性。另外IntentService的執(zhí)行還不受UI生命周期的影響,以此來確保AsyncTask能夠順利運行。
但是IntentService有下面幾個局限性:
雖然有上面那些限制,然而在在大多數(shù)情況下,IntentService都是執(zhí)行簡單后臺任務(wù)操作的理想選擇。
這節(jié)課會演示如何創(chuàng)建繼承的IntentService。同樣也會演示如何創(chuàng)建必須的回調(diào)方法onHandleIntent()
。最后,還會解釋如何在manifest文件中定義這個IntentService。
為你的app創(chuàng)建一個IntentService組件,需要自定義一個新的類,它繼承自IntentService,并重寫onHandleIntent()方法,如下所示:
public class RSSPullService extends IntentService {
@Override
protected void onHandleIntent(Intent workIntent) {
// Gets data from the incoming Intent
String dataString = workIntent.getDataString();
...
// Do work here, based on the contents of dataString
...
}
}
注意一個普通Service組件的其他回調(diào),例如onStartCommand()
會被IntentService自動調(diào)用。在IntentService中,要避免重寫那些回調(diào)。
IntentService需要在manifest文件添加相應(yīng)的條目,將此條目<service>
作為<application>
元素的子元素下進行定義,如下所示:
<application
android:icon="@drawable/icon"
android:label="@string/app_name">
...
<!--
Because android:exported is set to "false",
the service is only available to this app.
-->
<service
android:name=".RSSPullService"
android:exported="false"/>
...
<application/>
android:name
屬性指明了IntentService的名字。
注意<service>
標簽并沒有包含任何intent filter。因為發(fā)送任務(wù)給IntentService的Activity需要使用顯式Intent,所以不需要filter。這也意味著只有在同一個app或者其他使用同一個UserID的組件才能夠訪問到這個Service。
至此,你已經(jīng)有了一個基本的IntentService類,你可以通過構(gòu)造Intent對象向它發(fā)送操作請求。構(gòu)造這些對象以及發(fā)送它們到你的IntentService的方式,將在接下來的課程中描述。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: