HandlerThread & IntentService

HandlerThread 在 Android 中的一个具体应用场景就是 IntentService 。
IntentService 可用于执行后台耗时任务,当任务执行后会自动停止,同时由于 IntentService 是服务,所以它的优先级比单纯的线程要高,不容易被杀死。在实现上, IntentService 封装了 HandlerThread 和 Handler。
我们先来看下 onCreate() 方法

    @Override
    public void onCreate() {
        // TODO: It would be nice to have an option to hold a partial wakelock
        // during processing, and to have a static startService(Context, Intent)
        // method that would launch the service & hand off a wakelock.

        super.onCreate();
        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
        thread.start();

        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }

HandlerThread run 方法的具体实现

@Override
    public void run() {//线程体执行的内容
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();//获得一个Looper
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();//hook onLooperPrepared
        Looper.loop();//启动消息循环
        mTid = -1;
    }
  • HandlerThread本质上是一个线程类,它继承了Thread;
  • HandlerThread有自己的内部Looper对象,可以进行looper循环;
  • 通过获取HandlerThread的looper对象传递给Handler对象,可以在handleMessage方法中执行异步任务。
  • 创建HandlerThread后必须先调用HandlerThread.start()方法,Thread会先调用run方法,创建Looper对象。
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容