IntentService详解
来源:互联网 发布:js点击滑动到相应div 编辑:程序博客网 时间:2024/06/07 05:06
一、IntentService是什么?
IntentService 是继承自 Service 并处理异步请求的一个类,在 IntentService 内有一个工作线程来处理耗时操作,当任务执行完后,IntentService 会自动停止,不需要我们去手动结束。如果启动 IntentService 多次,那么每一个耗时操作会以工作队列的方式在 IntentService 的 onHandleIntent 回调方法中执行,依次去执行,执行完自动结束。
1、IntentService 本质上就是一种特殊的Service,继承自Service,是一个抽象类
2、它内部实现HandlerThread和Handler实现异步操作
二、IntentService的使用方法
MyIntentService代码:
public class MyIntentService extends IntentService { public MyIntentService() { //线程名称 super("MyIntentService"); } @Override public void onCreate() { super.onCreate(); } @Override protected void onHandleIntent(Intent intent) { //执行耗时操作 Thread.sleep(1000); } @Override public void onDestroy() { super.onDestroy(); }}
注册服务启动服务
// 在 Manifest 中注册服务<service android:name=".service.MyIntentService"/>// 像启动 Service 那样启动 IntentServiceIntent startIntent = new Intent(getActivity(), MyIntentService.class);startService(startIntent);
三、IntentService源码解析
1、先看IntentService源码:
// IntentService 源码中的 onCreate() 方法@Overridepublic void onCreate() { super.onCreate(); // HandlerThread 继承自 Thread,内部封装了 Looper,在这里新建线程并启动,所以启动 IntentService 不需要新建线程。 HandlerThread thread = new HandlerThread("IntentService[" + mName + "]"); thread.start(); // 获得工作线程的 Looper,并维护自己的工作队列。 mServiceLooper = thread.getLooper(); // mServiceHandler 是属于工作线程的。 mServiceHandler = new ServiceHandler(mServiceLooper);}private volatile ServiceHandler mServiceHandler;private final class ServiceHandler extends Handler { public ServiceHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { // onHandleIntent 方法在工作线程中执行,执行完调用 stopSelf() 结束服务。 onHandleIntent((Intent)msg.obj); stopSelf(msg.arg1); }}@WorkerThreadprotected abstract void onHandleIntent(Intent intent);
2、为什么多次启动 IntentService 会顺序执行事件,停止服务后,后续的事件得不到执行?
IntentService 中使用的 Handler、Looper、MessageQueue 机制把消息发送到线程中去执行的,所以多次启动 IntentService 不会重新创建新的服务和新的线程,只是把消息加入消息队列中等待执行,而如果服务停止,会清除消息队列中的消息,后续的事件得不到执行。
@Overridepublic void onStart(Intent intent, int startId) { Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; msg.obj = intent; mServiceHandler.sendMessage(msg);}@Overridepublic void onDestroy() { mServiceLooper.quit();}
阅读全文
0 0
- IntentService 详解
- IntentService 详解
- IntentService详解
- IntentService详解
- intentservice详解
- IntentService详解
- IntentService详解
- Android IntentService详解
- android intentService详解
- IntentService源码详解
- Android IntentService详解
- Android中IntentService详解
- Android IntentService详解
- Android中IntentService详解
- Android中IntentService详解
- Android中IntentService详解
- IntentService用法及其详解
- android IntentService详解
- 10 条提升 Android 性能的建议
- jsonp无X-Requested-With 及其深扒
- Node.js异步操作和CMD命令行下创建文件
- 获取当前文件夹的名字
- 为什么使用 NoSQL:NoSQL 与 SQL 的区别
- IntentService详解
- 卸载 Cloudera Manager 5.1.x.和 相关软件【官网翻译:高可用】
- java学习笔记(常量 二进制 其他进制 负数进制 变量 自动类型提升 强制类型转换 )
- CCNA第一天
- 单例设计模式及反射机制破坏
- LeetCode TwoSum题解
- 多线程,成员函数内创建线程,线程函数调用类内的其他成员函数
- if-else双选择结构
- jersey+maven构建restful服务