IntentService
是一个继承自Service的抽象类,要使用它就要创建它的子类。IntentService适合执行一些高优先级的后台任务,这样不容易被系统杀死。IntentService的onCreate
方法中会创建HandlerThread,并使用HandlerThread的Looper来构造一个Handler对象ServiceHandler,这样通过ServiceHandler对象发送的消息最终都会在HandlerThread中执行。IntentService会将Intent封装到Message中,通过ServiceHandler发送出去,在ServiceHandler的handleMessage
方法中会调用IntentService的抽象方法onHandleIntent
,所以IntentService的子类都要是实现这个方法。限制你的service的最好办法是使用IntentService, 它会在处理完交代给它的intent任务之后尽快结束自己。
IntentService特征:
- 会创建独立的worker线程来处理所有的Intent请求;
- 会创建独立的worker线程来处理onHandleIntent()方法实现的代码,无需处理多线程问题;
- 所有请求处理完成后,IntentService会自动停止,无需调用stopSelf()方法停止Service;
- 为Service的onBind()提供默认实现,返回null;
- 为Service的onStartCommand提供默认实现,将请求Intent添加到队列中;
Running in a Background Service:http://developer.android.com/training/run-background-service/index.html
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.
publicclassRSSPullService extends IntentService{
@Override
protectedvoid onHandleIntent(Intent workIntent){
// Gets data from the incoming Intent
String dataString = workIntent.getDataString();
...
// Do work here, based on the contents of dataString
...
}
}
<!--
Because android:exported is set to "false",
the service is only available to this app.
-->
<service
android:name=".RSSPullService"
android:exported="false"/>
Notice that the <service> element doesn't contain an intent filter.
Intent mServiceIntent =newIntent(getActivity(),RSSPullService.class);
mServiceIntent.setData(Uri.parse(dataUrl));
getActivity().startService(mServiceIntent);
to report the status of the request in an Activity object's UI. The recommended way to send and receive status is to use a LocalBroadcastManager, which limits broadcast Intent objects to components in your own app.
/*
* Creates a new Intent containing a Uri object
* BROADCAST_ACTION is a custom Intent action
*/
Intent localIntent =
newIntent(Constants.BROADCAST_ACTION)
// Puts the status into the Intent
.putExtra(Constants.EXTENDED_DATA_STATUS, status);
// Broadcasts the Intent to receivers in this app.
LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);
To receive broadcast Intent objects, use a subclass of BroadcastReceiver. In the subclass, implement the BroadcastReceiver.onReceive() callback method, which LocalBroadcastManager invokes when it receives an Intent. LocalBroadcastManager passes the incoming Intent to BroadcastReceiver.onReceive().