IntentService和HandlerThread

IntentService

概述

  • 处理异步请求的Service
  • 客户端使用startService()发送异步请求
  • 接收到客户端请求后开启一条后台工作线程处理请求
  • 在任务处理完毕后自动关闭
  • 不会阻塞主线程

使用方法

1.继承IntentService
2.构建一个无参构建函数
3.复写onHandleIntent(Intent intent)

源代码解析

private final class ServiceHandler extends Handler {
    public ServiewHandler(Looper looper) {
        super(looper);
    }
    @override
    public void handleMessage(Message msg) {
        onHandlerIntent((Intent)msg.obj);
        // 从这里可以看出只能使用startService(Intent)方式启动IntentService
        stopSelf(msg.arg1);
    }

}
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();
    // 创建一个后台线程,并获取一个Handler对象
    HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
    thread.start();
    mServiceLoper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);
}
public void onStartCommand() {
    // 回调onStart()方法实现处理
    onStart(intent,startid);
    return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
public void onStart() {
    // 获取后台线程的Handler,将Message发送给后台线程处理
    Message msg = mServiceHandler.obtainMessage();
    msg.arg1 = startId;
    msg.obj = intent;
    mServiceHandler.sendMessage(msg);
}

反思

  • 为什么会复写Service的onStart()方法?

在Service中@Deprecated的onStart()方法在IntentService中又被复写,如果新建一个方法可能更好


HandlerThread

概述

  • Handy class for starting a new Thread that has a looper.The looper can then be used to create handler classes.Note that start() must still be called.
源码解析
public void run() {
    mTid = Process.myTid();
    // 初始化Looper
    Looper.prepare();
    synchronized (this) {
        mLooper = Looper.myLooper();
        notifyAll();
    }
    Process.setThreadPriority(mPriority);
    onLooperPrepared();
    // Looper进行Message循环
    Looper.loop();
    mTid = -1;
}
/**
* This method returns the Looper associated with this thread. If this thread not been started or for any reason is isAlive() returns false, this method will return null.If this thread has been started, this method will block until the Looper has been initialized.
*/
public Looper getLooper() {
    if (!isAlive()) {
        return null;
    }
    syncchronized(this) {
        try { 
            wiat()
        } catch(InterruptedException e) {

        }
    }
    return mLooper;
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容