The IntentService class provides a straightforward structure for running an operation on a single background thread. This allows it to handle long-running operations without affecting your user interface's responsiveness. Also, an IntentService isn't affected by most user interface lifecycle events, so it continues to run in circumstances that would shut down an AsyncTask
//intentservice 提供了一個在後臺線程運行操做的簡潔的結構,他容許在不影響用戶界面響應的狀況下處理長時間運行的操做。intentservice不會受界面生命週期的影響,因此一樣的狀況asynctask可能會被結束可是intentservice還能夠繼續存活android
An IntentService has a few limitations:
// intent service有一些限制:
It can't interact directly with your user interface. To put its results in the UI, you have to send them to an Activity.
// 不能和界面交互,爲了讓結果更新到界面上必須將結果發送給activity
Work requests run sequentially. If an operation is running in an IntentService, and you send it another request, the request waits until the first operation is finished.
// 任務請求是順序執行的。若是一個操做此刻正在intentservice中執行,而後你發送另外一個請求,這個請求會等待,知道第一個請求任務結束
An operation running on an IntentService can't be interrupted.
// 運行中的操做不能被中斷
However, in most cases an IntentService is the preferred way to perform simple background operations.app
This lesson shows you how to create your own subclass of IntentService. The lesson also shows you how to create the required callback method onHandleIntent(). Finally, the lesson describes shows you how to define the IntentService in your manifest file.less
Create an IntentService
To create an IntentService component for your app, define a class that extends IntentService, and within it, define a method that overrides onHandleIntent(). For example:async
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
...
}
}
Notice that the other callbacks of a regular Service component, such as onStartCommand() are automatically invoked by IntentService. In an IntentService, you should avoid overriding these callbacks.
//注意 其餘的對於一般使用的service組件的其餘回調方法,例如onStartCommand會自動被intentservice調用,因此在intentservice中,你應該避免重寫這些回調ide
Define the IntentService in the Manifest
An IntentService also needs an entry in your application manifest. Provide this entry as a
<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/>
The attribute android:name specifies the class name of the IntentService.this
Notice that the
Now that you have the basic IntentService class, you can send work requests to it with Intent objects. The procedure for constructing these objects and sending them to your IntentService is described in the next lesson.code