IntentService是如何在子线程运行的。

来源:互联网 发布:mac新建文本文档 编辑:程序博客网 时间:2024/06/06 18:00

IntentService 是如何让服务运行在子线程的
IntentService是一个继承Service的抽象类。

public abstract class IntentService extends Service {    private volatile Looper mServiceLooper;    private volatile ServiceHandler mServiceHandler;    .....    }      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);        }    }        @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();        //工作线程 thread对象在run方法中创建,所以调用thread.start()后,本线程的looper对象和消息队列就创建完成了        mServiceLooper = thread.getLooper();        //handled对象关联thread线程中的looper对象 和 消息队列。        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);    }

//服务运行时,handle封装Message对象。加入到
对应的消息队列中,looper对象就会去遍历消息队列
取出Message对象,并调用器msg.target.dispatchMessage(msg);
looper是在运行在子线程中的,所以handler处理消息也是在子线程。这样就实现了把任务添加到工作线程中执行。

阅读全文
0 0
原创粉丝点击