简介
IntentService,异步处理服务,新开一个线程(handlerThread),在线程中发消息,然后接受处理完成后,会清理线程,并且关掉服务。
特点
IntentService有以下特点:
(1) 它创建了一个独立的工作线程来处理所有的通过onStartCommand()传递给服务的intents。
(2) 创建了一个工作队列,来逐个发送intent给onHandleIntent()。
(3) 不需要主动调用stopSelft()来结束服务。因为,在所有的intent被处理完后,系统会自动关闭服务。
(4) 默认实现的onBind()返回null。
(5) 默认实现的onStartCommand()的目的是将intent插入到工作队列中。
使用
继承IntentService的类至少要实现两个函数:构造函数和onHandleIntent()函数。
public class IntentServiceSub extends IntentService {
private static final String TAG = "IntentServiceSub";
public IntentServiceSub() {
super("IntentServiceSub");
Log.i(TAG, "=>IntentServiceSub");
}
/* (non-Javadoc)
* @see android.app.IntentService#onCreate()
*/
@Override
public void onCreate() {
Log.i(TAG, "=>onCreate");
super.onCreate();
}
/* (non-Javadoc)
* @see android.app.IntentService#onDestroy()
*/
@Override
public void onDestroy() {
Log.i(TAG, "=>onDestroy");
super.onDestroy();
}
@Override
protected void onHandleIntent(Intent arg0) {
Log.i(TAG, "IntentService 线程:"+Thread.currentThread.getId());
Thread.sleep(2000);
}
}