IntentService

 
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特征:
  1. 会创建独立的worker线程来处理所有的Intent请求; 
  2. 会创建独立的worker线程来处理onHandleIntent()方法实现的代码,无需处理多线程问题; 
  3. 所有请求处理完成后,IntentService会自动停止,无需调用stopSelf()方法停止Service; 
  4. 为Service的onBind()提供默认实现,返回null; 
  5. 为Service的onStartCommand提供默认实现,将请求Intent添加到队列中; 
 
 
 

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. 

 
  1. publicclassRSSPullService extends IntentService{
  2.     @Override
  3.     protectedvoid onHandleIntent(Intent workIntent){
  4.         // Gets data from the incoming Intent
  5.         String dataString = workIntent.getDataString();
  6.         ...
  7.         // Do work here, based on the contents of dataString
  8.         ...
  9.     }
  10. }
 
  1.     <!--
  2.             Because android:exported is set to "false",
  3.             the service is only available to this app.
  4.         -->
  5.         <service
  6.             android:name=".RSSPullService"
  7.             android:exported="false"/>
Notice that the <service> element doesn't contain an intent filter.
  1. Intent mServiceIntent =newIntent(getActivity(),RSSPullService.class);
  2. mServiceIntent.setData(Uri.parse(dataUrl));
  3. 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.
  1. /*
  2.      * Creates a new Intent containing a Uri object
  3.      * BROADCAST_ACTION is a custom Intent action
  4.      */
  5.     Intent localIntent =
  6.             newIntent(Constants.BROADCAST_ACTION)
  7.             // Puts the status into the Intent
  8.             .putExtra(Constants.EXTENDED_DATA_STATUS, status);
  9.     // Broadcasts the Intent to receivers in this app.
  10.     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().