IntentService解析
来源:互联网 发布:有20个usb端口的电脑 编辑:程序博客网 时间:2024/06/12 01:02
IntentService使用一个工作队列来从Application的主线程中分担任务,这些任务往往做着比较耗时的工作。IntentService维护着一个工作线程消息处理对象(Handler),通过在工作线程中创建消息循环(Looper)和消息队列(MessageQueue)来以队列的方式处理任务,一次只能处理一个任务,上一个任务请求完成后才接着处理下一个任务请求。
IntentService继承自Service,也就是说IntentService具有Service的一切特性。客户端可以通过startService(Intent) 来发送一个任务请求,如果IntentService还未创建的话,会调用onCreate()方法
@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();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler( mServiceLooper);
}
在onCreate()方法中会启动工作线程(HandlerThread)并获取工作线程的消息循环对象(Looper),接着实例化处理工作线程消息队列中消息的Handler对象(ServiceHandler)。做好以上准备工作后,在onStart(Intent intent, int startId) 方法中发送一条任务消息请求 ,接着就是在ServiceHandler中进行消息处理了
@Override
public void onStart(Intent intent, int startId) {
Message msg = mServiceHandler .obtainMessage();
msg. arg1 = startId;
msg. obj = intent;
mServiceHandler .sendMessage(msg);
}
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);
}
}
我们可以看到只要覆写onHandleIntent(Intent)方法来处理耗时的任务就行了。不难发现IntentService正是通过工作线程的消息循环(Looper)来消费客户端发来的任务请求(存储在工作线程消息队列中(MessageQueue))
IntentService继承自Service,拥有Service的一切特性。IntentService内部发送和消费任务请求(由工作线程的消息循环和消息队列来处理)。更多的细节还应该仔细看看IntentService和HandlerThread的源码
- IntentService解析
- IntentService解析
- IntentService解析
- IntentService解析
- intentService解析
- IntentService解析
- Android IntentService解析
- Android IntentService完全解析
- IntentService源码解析
- IntentService 源码解析
- Android IntentService 源码解析
- 【IntentService】原理解析
- Android IntentService 使用解析
- IntentService从源码解析
- Anroid IntentService解析
- IntentService用法解析
- Android IntentService解析
- Andorid IntentService 完全解析
- 易语言零基础新手入门教程 第二课
- C#相等比较用法总结
- 想你的 夜
- 如何编程判别一个Revit族的主题对象是墙还是基于面?
- 函数返回 局部变量问题
- IntentService解析
- Ehlib 的 DBGridEh 控件导出到Excel的三种封装过程/函数
- [C# 基础知识系列]专题一:深入解析委托——C#中为什么要引入委托
- 减少文件特征码的一些方法与技巧
- 一种保护眼睛的好方法
- 浏览器是如何工作的系列:CSS2可视化模型
- 问题11:双链表的相关操作
- 详谈 vc++源码免杀全套思路方法
- fight club