編寫:kesenhoo - 原文:http://developer.android.com/training/run-background-service/create-service.html
IntentService為在單一后臺(tái)線程中執(zhí)行任務(wù)提供了一種直接的實(shí)現(xiàn)方式。它可以處理一個(gè)耗時(shí)的任務(wù)并確保不影響到UI的響應(yīng)性。另外IntentService的執(zhí)行還不受UI生命周期的影響,以此來確保AsyncTask能夠順利運(yùn)行。
但是IntentService有下面幾個(gè)局限性:
雖然有上面那些限制,然而在在大多數(shù)情況下,IntentService都是執(zhí)行簡單后臺(tái)任務(wù)操作的理想選擇。
這節(jié)課會(huì)演示如何創(chuàng)建繼承的IntentService。同樣也會(huì)演示如何創(chuàng)建必須的回調(diào)方法onHandleIntent()。最后,還會(huì)解釋如何在manifest文件中定義這個(gè)IntentService。
為你的app創(chuàng)建一個(gè)IntentService組件,需要自定義一個(gè)新的類,它繼承自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
...
}
}
注意一個(gè)普通Service組件的其他回調(diào),例如onStartCommand()會(huì)被IntentService自動(dòng)調(diào)用。在IntentService中,要避免重寫那些回調(diào)。
IntentService需要在manifest文件添加相應(yīng)的條目,將此條目<service>作為<application>元素的子元素下進(jìn)行定義,如下所示:
<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>標(biāo)簽并沒有包含任何intent filter。因?yàn)榘l(fā)送任務(wù)給IntentService的Activity需要使用顯式Intent,所以不需要filter。這也意味著只有在同一個(gè)app或者其他使用同一個(gè)UserID的組件才能夠訪問到這個(gè)Service。
至此,你已經(jīng)有了一個(gè)基本的IntentService類,你可以通過構(gòu)造Intent對(duì)象向它發(fā)送操作請(qǐng)求。構(gòu)造這些對(duì)象以及發(fā)送它們到你的IntentService的方式,將在接下來的課程中描述。