IntentService和HandlerThread

2017-03-24  本文已影响0人  jiaozi0203

IntentService

概述

使用方法

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中@Deprecated的onStart()方法在IntentService中又被复写,如果新建一个方法可能更好


HandlerThread

概述

源码解析
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;
}
上一篇 下一篇

猜你喜欢

热点阅读