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;
}

你可能感兴趣的:(IntentService和HandlerThread)