IntentService源码分析
和HandlerThread一样,IntentService也是Android替我们封装的一个Helper类,用来简化开发流程的。接下来分析源码的时候
你就明白是怎么回事了。IntentService是一个按需处理用Intent表示的异步请求的基础Service类,本质上还是Android Service。
客户端通过Context#startService(Intent);这样的代码来发起一个请求。Service只在没启动的情况下启动,并且在一个worker thread
中处理所有的异步请求,当所有的请求处理完毕时IntentService会自动停止,所以你不需要显式的stop它。关于客户端代码如何正确的
使用它,请参看官方文档 https://developer.android.com/training/run-background-service/create-service.html。
接着和以往一样,我们先来看看关键字段和ctor:
private volatile Looper mServiceLooper; // 这2者都是和HandlerThread关联的,只是没明白这里为什么需要volatile关键字
private volatile ServiceHandler mServiceHandler; // 看起来他们都只是在UI线程中被访问了,似乎并没有什么并发问题。。。
private String mName;
private boolean mRedelivery; /**
* 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;
}
接下来看点有意思的代码:
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
} @Override
public void handleMessage(Message msg) { // 基于我们前面关于Handler的介绍,这些代码都很容易理解
onHandleIntent((Intent)msg.obj); // 注意这个Template方法,这是我们的子类中真正处理请求的地方
stopSelf(msg.arg1); // 注意看这里调用的是带参数的stopSelf并不是无参版本的stopSelf(),
} // 这是因为IntentService并不是处理完一个请求就退出,而是所有请求。
} /**
* Sets intent redelivery preferences. Usually called from the constructor
* with your preferred semantics.
*
* <p>If enabled is true,
* {@link #onStartCommand(Intent, int, int)} will return
* {@link Service#START_REDELIVER_INTENT}, so if this process dies before
* {@link #onHandleIntent(Intent)} returns, the process will be restarted
* and the intent redelivered. If multiple Intents have been sent, only
* the most recent one is guaranteed to be redelivered.
*
* <p>If enabled is false (the default),
* {@link #onStartCommand(Intent, int, int)} will return
* {@link Service#START_NOT_STICKY}, and if the process dies, the Intent
* dies along with it.
*/
public void setIntentRedelivery(boolean enabled) { // 设置是否重新发送Intent,一般在ctor中设置
mRedelivery = enabled; // 具体内容请详细阅读方法的doc
} @Override
public void onCreate() { // 此方法只在第一次需要创建service的时候调用
// 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(); // 启动接下来处理客户端异步请求的HandlerThread mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper); // 拿到与之关联的Handler,用来向它发送待处理的消息(即客户端请求)
}
接下来看2个onStartXXX相关的方法:
@Override
public void onStart(Intent intent, int startId) { // 其所作的事情就是根据参数获得一个对应的Message,
Message msg = mServiceHandler.obtainMessage(); // send一个Message而已,消息的处理会在ServiceHandler
msg.arg1 = startId; // 的handleMessage方法中进行
msg.obj = intent; // 稍后我们分析下这里的startId咋来的
mServiceHandler.sendMessage(msg);
} /**
* You should not override this method for your IntentService. Instead,
* override {@link #onHandleIntent}, which the system calls when the IntentService
* receives a start request.
* @see android.app.Service#onStartCommand
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY; // 根据mRedelivery返回不同的策略值
}
这里我们解释下int startId的来历。首先我们说下这部分代码frameworks\base\services\java\com\android\server\am\,
这个目录下面有很多对Android内部机制来说很重要的类(比如“很有名”的ANR dialog就在这里)。与startId相关的2个类分别是
ServiceRecord和ActiveServices,这里我们看下ServiceRecord中与startId相关的代码,如下:
private int lastStartId; // identifier of most recent start request. public int getLastStartId() {
return lastStartId;
} public int makeNextStartId() { // 此方法的调用是在ActiveServices中
lastStartId++;
if (lastStartId < 1) { // 通过代码我们可以看到startId是从1开始的正整数,每次+1
lastStartId = 1; // 你可以理解成客户端请求的次数(即startService调用的次数)
}
return lastStartId;
}
这一点代码就完全解释了我们一直以来的困惑,像我自己一直以来就不理解这里的startId是干嘛用的,咋来的。
接下来我们看一组stopXXX相关的方法:
/**
* Stop the service, if it was previously started. This is the same as
* calling {@link android.content.Context#stopService} for this particular service.
*
* @see #stopSelfResult(int)
*/
public final void stopSelf() { // 内部调用参数为-1的版本,此方法会停止service
stopSelf(-1);
} /**
* Old version of {@link #stopSelfResult} that doesn't return a result.
*
* @see #stopSelfResult
*/
public final void stopSelf(int startId) { // 参数startId要么是-1要么是从1开始的正整数,只有它等于我们最后一次调用
if (mActivityManager == null) { // startService时,onStartCommand里传递进来的startId值时,
return; // service才会停止,否则并不会停止service。service会在处理完
} // 所有的客户端请求后自动停止。比如客户端调用了10次startService来
try { // 发出多个请求,那么只有当这里的startId == 10的时候,service才会停止,
mActivityManager.stopServiceToken(// 其onDestroy方法才会被调用。另外由于我们的请求总是串行处理的,所以永远不会
new ComponentName(this, mClassName), mToken, startId); // 出现先stopSelf(10)再stopSelf(9)这种情况。
} catch (RemoteException ex) {
}
} /**
* Stop the service if the most recent time it was started was
* <var>startId</var>. This is the same as calling {@link
* android.content.Context#stopService} for this particular service but allows you to
* safely avoid stopping if there is a start request from a client that you
* haven't yet seen in {@link #onStart}.
*
* <p><em>Be careful about ordering of your calls to this function.</em>.
* If you call this function with the most-recently received ID before
* you have called it for previously received IDs, the service will be
* immediately stopped anyway. If you may end up processing IDs out
* of order (such as by dispatching them on separate threads), then you
* are responsible for stopping them in the same order you received them.</p>
*
* @param startId The most recent start identifier received in {@link
* #onStart}.
* @return Returns true if the startId matches the last start request
* and the service will be stopped, else false.
*
* @see #stopSelf()
*/
public final boolean stopSelfResult(int startId) { // 此方法基本同上,不赘述,后面我们刨根问底下stopServiceToken到底咋实现的,
if (mActivityManager == null) { // 看看这里startId是-1和正整数到底有啥区别。
return false;
}
try {
return mActivityManager.stopServiceToken(
new ComponentName(this, mClassName), mToken, startId);
} catch (RemoteException ex) {
}
return false;
} @Override
public void onDestroy() { // 处理完所有客户端请求,stop service的时候会被调到,退出looper。
mServiceLooper.quit();
} /**
* Unless you provide binding for your service, you don't need to implement this
* method, because the default implementation returns null.
* @see android.app.Service#onBind
*/
@Override
public IBinder onBind(Intent intent) { // 当你只是个started service的时候,默认实现就足够了。
return null;
} /**
* This method is invoked on the worker thread with a request to process.
* Only one Intent is processed at a time, but the processing happens on a
* worker thread that runs independently from other application logic.
* So, if this code takes a long time, it will hold up other requests to
* the same IntentService, but it will not hold up anything else.
* When all requests have been handled, the IntentService stops itself,
* so you should not call {@link #stopSelf}.
*
* @param intent The value passed to {@link
* android.content.Context#startService(Intent)}.
*/
protected abstract void onHandleIntent(Intent intent); // handleMessage中定义的模板方法,也即我们处理请求的逻辑发生的地方
As promised, 最后让我们看下stopServiceToken究竟做了什么,代码如下:
public boolean stopServiceToken(ComponentName className, IBinder token, // ActivityManagerService.java中的方法
int startId) {
synchronized(this) {
return mServices.stopServiceTokenLocked(className, token, startId);
}
} boolean stopServiceTokenLocked(ComponentName className, IBinder token, // ActiveServices.java中的方法
int startId) {
if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
+ " " + token + " startId=" + startId);
ServiceRecord r = findServiceLocked(className, token, UserHandle.getCallingUserId());
if (r != null) {
if (startId >= 0) { // 注意这个判断,和我们猜测的一样
// Asked to only stop if done with all work. Note that
// to avoid leaks, we will take this as dropping all
// start items up to and including this one.
ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
if (si != null) {
while (r.deliveredStarts.size() > 0) {
ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
cur.removeUriPermissionsLocked();
if (cur == si) {
break;
}
}
} if (r.getLastStartId() != startId) { // 这句代码是所有疑惑的答案
return false; // 如果不是最后一个请求的startId,直接返回了,并没有往下面执行;
} // 这也就解释了为啥非last startId不能让service停止的原因。 if (r.deliveredStarts.size() > 0) {
Slog.w(TAG, "stopServiceToken startId " + startId
+ " is last, but have " + r.deliveredStarts.size()
+ " remaining args");
}
} synchronized (r.stats.getBatteryStats()) {
r.stats.stopRunningLocked();
}
r.startRequested = false;
if (r.tracker != null) {
r.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
SystemClock.uptimeMillis());
}
r.callStart = false;
final long origId = Binder.clearCallingIdentity();
bringDownServiceIfNeededLocked(r, false, false); // 真正让service停止的代码
Binder.restoreCallingIdentity(origId);
return true;
}
return false;
}
至此IntentService相关的代码都已经分析完毕了。
IntentService源码分析的更多相关文章
- IntentService使用以及源码分析
一 概述 我们知道,在Android开发中,遇到耗时的任务操作时,都是放到子线程去做,或者放到Service中去做,在Service中开一个子线程来执行耗时操作. 那么,在Service里面我们需要自 ...
- Android HandlerThread 源码分析
HandlerThread 简介: 我们知道Thread线程是一次性消费品,当Thread线程执行完一个耗时的任务之后,线程就会被自动销毁了.如果此时我又有一 个耗时任务需要执行,我们不得不重新创建线 ...
- IntentService源码
原文地址IntentService源码分析 @Override public void onCreate() { super.onCreate(); HandlerThread thread = ne ...
- Android源码分析-消息队列和Looper
转载请注明出处:http://blog.csdn.net/singwhatiwanna/article/details/17361775 前言 上周对Android中的事件派发机制进行了分析,这次博主 ...
- Android异步消息传递机制源码分析
1.Android异步消息传递机制有以下两个方式:(异步消息传递来解决线程通信问题) handler 和 AsyncTask 2.handler官方解释的用途: 1).定时任务:通过handler.p ...
- ABP源码分析一:整体项目结构及目录
ABP是一套非常优秀的web应用程序架构,适合用来搭建集中式架构的web应用程序. 整个Abp的Infrastructure是以Abp这个package为核心模块(core)+15个模块(module ...
- HashMap与TreeMap源码分析
1. 引言 在红黑树--算法导论(15)中学习了红黑树的原理.本来打算自己来试着实现一下,然而在看了JDK(1.8.0)TreeMap的源码后恍然发现原来它就是利用红黑树实现的(很惭愧学了Ja ...
- nginx源码分析之网络初始化
nginx作为一个高性能的HTTP服务器,网络的处理是其核心,了解网络的初始化有助于加深对nginx网络处理的了解,本文主要通过nginx的源代码来分析其网络初始化. 从配置文件中读取初始化信息 与网 ...
- zookeeper源码分析之五服务端(集群leader)处理请求流程
leader的实现类为LeaderZooKeeperServer,它间接继承自标准ZookeeperServer.它规定了请求到达leader时需要经历的路径: PrepRequestProcesso ...
随机推荐
- 在浏览器输入网址到页面加载完毕中间到底发生了什么?(Browser-->Server)
最近在学习韩老师的php视频,中间有讲到发送请求到服务器返回内容,以前对这个理解并不深刻,虽然以前也知道一部分,这次听了之后收获良多:所以我就画了个流程图,从浏览器输入网址到服务器返回信息,浏览器渲染 ...
- JAVA - 优雅的记录日志(log4j实战篇)
写在前面 项目开发中,记录错误日志有以下好处: 方便调试 便于发现系统运行过程中的错误 存储业务数据,便于后期分析 在java中,记录日志有很多种方式: 自己实现 自己写类,将日志数据,以io操作方式 ...
- [开源 .NET 跨平台 数据采集 爬虫框架: DotnetSpider] [三] 配置式爬虫
[DotnetSpider 系列目录] 一.初衷与架构设计 二.基本使用 三.配置式爬虫 四.JSON数据解析与配置系统 上一篇介绍的基本的使用方式,虽然自由度很高,但是编写的代码相对还是挺多.于是框 ...
- ASP.NET MVC ModelValidator小结
当用户通过UI输入数据向程序交互时,都会出现一个潜在的错误,数据错误,要检查用户提交的数据是否正确,需要做数据验证,在ASP.NET MVC中,每当Action执行前都会对传入Action的Model ...
- 关于.net页面提交后css样式不生效的发现
一直以来没有解决的问题,今天在老师的提示下终于得到解决. 问题:asp.net页面,提交后,或者举例最简单的例子通俗的说,当登陆页面,某一项输入错误,并且使用Response.Write(" ...
- 其实Unix很简单
很多编程的朋友都在网上问我这样的几个问题,Unix怎么学?Unix怎么这么难?如何才能学好?并且让我给他们一些学好Unix的经验.在绝大多数时候,我发现问这些问题的朋友都有两个特点: 1)对Unix有 ...
- .net批量上傳Csv檔資料應用程序開發總結
應用環境:visual studio 2010開發工具,Database為Sql2008以上版本 最近在生產環境中需要開發一款應用程式,上傳電子檔(.csv)資料至Database 最初方案: 以tx ...
- [控件] 加强版 TOneSelection (改良自 Berlin 10.1 TSelection)
本控件修改自 Delphi Berlin 10.1 的 TSelection (FMX.Controls.pas) 修改重点: 移动点显示在上方 增加(左中,上中,右中,下中)控制点,含原来的总共有 ...
- Firemonkey ListView 点击事件
Firemonkey ListView 的点击事件一直让人摸不着头绪(各平台触发规则不太相同),因为它提供了点击相关的事件就有如下: OnChange:改变项目触发. OnClick:点击触发. On ...
- java Servlet+mysql 调用带有输入参数和返回值的存储过程(原创)
这个数据访问的功能,我在.NET+Mysql .NET+Sqlserver PHP+Mysql上都实现过,并且都发布在了我博客园里面,因为我觉得这个功能实在是太重要,会让你少写很多SQL语句不说,还 ...