IntentService源码分析以及HandlerThread的用法

来源:互联网 发布:苹果手机更改网络制式 编辑:程序博客网 时间:2024/05/19 20:56

直接上源码:

public abstract class IntentService extends Service {    private volatile Looper mServiceLooper;    private volatile ServiceHandler mServiceHandler;    private String mName;    private boolean mRedelivery;    private final class ServiceHandler extends Handler {        public ServiceHandler(Looper looper) {            super(looper);        }        @Override        public void handleMessage(Message msg) {            onHandleIntent((Intent)msg.obj);            stopSelf(msg.arg1);        }    }    public IntentService(String name) {        super();        mName = name;    }    public void setIntentRedelivery(boolean enabled) {        mRedelivery = enabled;    }    @Override    public void onCreate() {        super.onCreate();        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");        thread.start();        mServiceLooper = thread.getLooper();        mServiceHandler = new ServiceHandler(mServiceLooper);    }    @Override    public void onStart(Intent intent, int startId) {        Message msg = mServiceHandler.obtainMessage();        msg.arg1 = startId;        msg.obj = intent;        mServiceHandler.sendMessage(msg);    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        onStart(intent, startId);        return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;    }    @Override    public void onDestroy() {        mServiceLooper.quit();    }    @Override    public IBinder onBind(Intent intent) {        return null;    }    protected abstract void onHandleIntent(Intent intent);}


HandlerThread部分源码:

public class HandlerThread extends Thread {    int mPriority;    int mTid = -1;    Looper mLooper;    public HandlerThread(String name) {        super(name);        mPriority = Process.THREAD_PRIORITY_DEFAULT;    }---    @Override    public void run() {        mTid = Process.myTid();        Looper.prepare();        synchronized (this) {            mLooper = Looper.myLooper();            notifyAll();        }        Process.setThreadPriority(mPriority);        onLooperPrepared();        Looper.loop();        mTid = -1;    }---}


分析:

IntentService继承自Service,是一个抽象类。

调用onCreate()方法时就new了一个HandlerThread和ServiceHandler对象,IntentService不会轻易被系统杀死。

调用startService()方法时,IntentService会把传递来的参数封装成Message并通过ServiceHandler进行发送。

接着ServiceHandler会调用onHandleIntent()方法来处理这个Message,处理完成后就会调用stopSelf()方法来结束自己。

HandlerThread继承自Thread,使用可以参考IntentService使用HandlerThread的用法。

0 0
原创粉丝点击