IntentServie源码解析
来源:互联网 发布:淘宝购物车的东西少了 编辑:程序博客网 时间:2024/05/16 12:58
IntentService是Service的子类,默认Service运行在应用所在进程的主线程中,如果要在后台执行耗时任务,需要创建子线程,IntentService即可以满足这样的需求,它封装了一个work-thread,处理接收到的Intent,它可以处理多个请求,但一次只能处理一个。
下面看下它的源码。
/** * Creates an IntentService. Invoked by your subclass's constructor. * * @param name Used to name the worker thread, important only for debugging. */ public IntentService(String name) { super(); mName = name; }
IntentService的构造方法,IntentService的实现类的构造方法需要调用该构造方法,向其传递一个name,该name用于命名worker-thread,debug时用得着。
@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实例,并start它,然后HandlerThread从其MessageQueue中轮寻消息,有则处理,没有则等待。创建ServiceHandler的实例,当HandlerThread取到消息,其会回调ServiceHandler的handleMessage()方法。
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); } }
在ServiceHandler的handleMessage()方法实现中,其调用了onHandleIntent(),该方法即是IntentService的子类必须实现的方法,onHandleIntent()最终会在worker-thread中执行,当onHandleIntent()返回,调用stopSelf(intstartId)方法,如果startId是最新startService()的id,就停掉服务,如果不是,则不停,等待其他request完成。
@Override public void onStart(Intent intent, int startId) { Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; msg.obj = intent; mServiceHandler.sendMessage(msg); }
在onStart()方法中用ServiceHandler向worker-thread发消息。
@Override public void onDestroy() { mServiceLooper.quit(); }
当服务被销毁时停掉worker-thread。
0 0
- IntentServie源码解析
- 源码解析
- 源码解析
- 【JDk源码解析之一】ArrayList源码解析
- 【源码解析】-- ArrayList的源码解析
- EventBus源码解析(史上最全的源码解析)
- 【源码】Vector、Stack源码解析
- Sping源码解析-源码下载
- <Android源码>IntentService源码解析
- JAVA源码解析-String源码
- JAVA源码解析-ArrayList源码
- JAVA源码解析-LinkedList源码
- Spark源码-SparkContext源码解析
- Jboss源码解析
- 网页病毒源码解析
- strlen源码解析
- chrome源码解析系列
- gnash源码解析
- PHP中各种数据类型的区别和转换方法
- Like 的用法
- 获得计算机名、用户名
- Java实现数据结构之二叉查找树
- UNIX网络编程卷一:第六章 I/O 复用 select, poll
- IntentServie源码解析
- 嵌入式uC/OS-2的任务管理
- Highchart构建横向误差条图
- java中类与接口的一些常见困惑
- Datagridview加右键菜单功能
- 计算数据库中各个表的数据量和每行记录所占用空间
- 用MyEclipse10开发基于JAX-WS的Web Service实例
- 微分
- Java的JAR包, EAR包 ,WAR包中区别?