美文网首页我爱编程
组件之IntentService详解

组件之IntentService详解

作者: kjy_112233 | 来源:发表于2017-08-04 15:57 被阅读0次

一、IntentService解析

(1)IntentService的特点

  • IntentService自带一个工作线程,当我们的Service需要做一些可能会阻塞主线程的工作的时候可以考虑使用IntentService。
  • IntentService通过在onCreate中创建HandlerThread线程、在onStartCommand发送消息到IntentService内部类ServiceHandler中,在handleMessage中调用onHandleIntent在子线程完成工作。
  • 当我们通过startService多次启动IntentService会产生多个Message消息。由于IntentService只持有一个工作线程,所以每次onHandleIntent只能处理一个Message消息,IntentService不能并行的执行多个intent,只能一个一个的按照先后顺序完成,当所有消息完成的时候IntentService就销毁了,会执行onDestroy回调方法。
    (2)IntentService实现类
public class DownLoadIntentService extends IntentService {
    
    public DownLoadIntentService(String name) {
        super(name);
    }
    //运行在主线程
    @Override
    public void onCreate() {
        super.onCreate();
    }

    //运行在主线程
    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    //在子线程中执行
    @Override
    protected void onHandleIntent(@Nullable Intent intent) {

    }
}

组件之IntentService源码解析

相关文章

网友评论

    本文标题:组件之IntentService详解

    本文链接:https://www.haomeiwen.com/subject/hqnvlxtx.html