总的来说:IntentService它不像Service要手动创建线程,它会自己创建一个线程,多个任务按顺序进行,
使用案例:
//构造方法 一定要实现此方法否则Service运行出错。
public MyIntentService() {
super("MyIntentService");
}
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate");
sendServiceState("onCreate");
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.i(TAG, "");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.i(TAG, "onHandleIntent thread:"+Thread.currentThread());
String action = intent.getAction();
if(action.equals(ACTION_DOWN_IMG)){
for(int i = 0; i < 100; i++){
try{ //模拟耗时操作
Thread.sleep(50);
}catch (Exception e) {
}
sendProgress(i);
}
}else if(action.equals(ACTION_DOWN_VID)){
for(int i = 0; i < 100; i++){
try{ //模拟耗时操作
Thread.sleep(70);
}catch (Exception e) {
}
sendProgress(i);
}
}
Log.i(TAG, "onHandleIntent end");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy");
sendServiceState("onDestroy");
}
只需要重写OnHandleIntent方法,在其中处理耗时逻辑即可;若想把值传出,可用接口回调或者广播;
源码分析:
首先在onCreate方法中创建了HandleThread对象,获取子线程中的Looper,将Looper与创建的Handle绑定
然后在onStart方法中,HandleThread对象将消息发送到消息队列中,后面基本都和handle源码一样,消息队列中的消息取出
交给Handle对象的handlemessage方法处理,我们重写的OnIntentService方法就是在handlemessage中用来处理逻辑的;
顺便说下HandleThread使用方法:
创建HandleThread对象,获取子线程中Looper,将Looper与创建的Handle绑定,(不像Handle要自己创建Looper对象,然后与当前线程进行绑定)这样就可以在handlemessage中处理逻辑
然后利用Handle对象sendmessage方法,发送消息