IntentService和HandlerThread的使用以及源码阅读
使用
MyIntentService.java
public class MyIntentService extends IntentService {
/**
* 是否正在运行
*/
private boolean isRunning;
/**
*进度
*/
private int count;
public MyIntentService() {
super("test");
}
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public MyIntentService(String name) {
super(name);
}
@Override
protected void onHandleIntent(Intent intent) {
Logout.e("onHandleIntent"+intent.getStringExtra("name"));
try {
Thread.sleep(1000);
isRunning = true;
count = 0;
while (isRunning) {
count++;
if (count >= 100) {
isRunning = false;
}
Thread.sleep(50);
Logout.e("线程运行中..."+ count);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
Logout.e("结束了任务");
}
@Override
public void onDestroy() {
super.onDestroy();
Logout.e("线程结束运行..." + count);
}
public static class Logout{
private static final String TAG = "Logout";
public static void e(String conent){
Log.d(TAG, "e: "+conent);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
public classTestActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_async_task);
startService(new Intent(this, MyIntentService.class));
new Handler().post(new Runnable() {
@Override
public void run() {
//延迟一段时间,发送第二次消息
Intent intent = new Intent(AsyncTaskActivity.this, MyIntentService.class);
intent.putExtra("name", "helloWorld");
startService(intent);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
// handlerThread.quit();
// unbindService(serviceConnection);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
上面就是简单的使用IntentService的教程。 IntentService是一个抽象类,所以需要自己集成实现,这里有两点需要注意。
自己实现的类需要提供无参的构造函数
IntentService 是在onHandleIntent中处理耗时操作,这里的intent 就是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();
//构造一个IntentService,并启动
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
//使用HandlerThread 的looper 构造一个handler,这样就可以从HandlerThread接收发送消息
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
HandlerThread中比较值得关注的就是run方法。
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
这里的代码也比较简单,流程基本上就是在非ui thread中构建Handler的标准流程,然后会走到 Looper.loop();中进入死循环。所以HandlerThread在使用结束以后,需要记得调用quit方法,停止死循环。
关注完oncreate方法,我们来着重观察一下IntentServcie的onstart 和 onStartCommand方法
@Override
public void onStart(Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
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;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
可以看到这里利用了onStartCommand 每次startService每次都会调用onStartCommand的特点,用来给IntentService传递消息。IntentService收到消息后,就会调用mServiceHandler 将消息发送出去。这里主要的作用是将主线程的信息传递到HandlerThread。所以接下来,我们来看下ServiceHandler的具体的实现。
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);
}
}
---------------------
IntentService和HandlerThread的使用以及源码阅读的更多相关文章
- 【原】FMDB源码阅读(三)
[原]FMDB源码阅读(三) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 FMDB比较优秀的地方就在于对多线程的处理.所以这一篇主要是研究FMDB的多线程处理的实现.而 ...
- 【原】FMDB源码阅读(二)
[原]FMDB源码阅读(二) 本文转载请注明出处 -- polobymulberry-博客园 1. 前言 上一篇只是简单地过了一下FMDB一个简单例子的基本流程,并没有涉及到FMDB的所有方方面面,比 ...
- 【原】FMDB源码阅读(一)
[原]FMDB源码阅读(一) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 说实话,之前的SDWebImage和AFNetworking这两个组件我还是使用过的,但是对于 ...
- 【原】AFNetworking源码阅读(六)
[原]AFNetworking源码阅读(六) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 这一篇的想讲的,一个就是分析一下AFSecurityPolicy文件,看看AF ...
- 【原】AFNetworking源码阅读(五)
[原]AFNetworking源码阅读(五) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 上一篇中提及到了Multipart Request的构建方法- [AFHTTP ...
- 【原】AFNetworking源码阅读(四)
[原]AFNetworking源码阅读(四) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 上一篇还遗留了很多问题,包括AFURLSessionManagerTaskDe ...
- 【原】AFNetworking源码阅读(三)
[原]AFNetworking源码阅读(三) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 上一篇的话,主要是讲了如何通过构建一个request来生成一个data tas ...
- 【原】AFNetworking源码阅读(二)
[原]AFNetworking源码阅读(二) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 上一篇中我们在iOS Example代码中提到了AFHTTPSessionMa ...
- 【原】AFNetworking源码阅读(一)
[原]AFNetworking源码阅读(一) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 AFNetworking版本:3.0.4 由于我平常并没有经常使用AFNetw ...
随机推荐
- 小议C#错误调试和异常处理
在程序设计中不可避免地会出现各种各样的错误,在编写代码时须要尽量避免. 在处理错误时,首先应该分析错 误的类型,找出出错的原因才干解决错误. 错误的分类 watermark/2/text/aHR0cD ...
- BZOJ 3439 Kpm的MCpassword Trie树+可持久化线段树
题目大意:给定n个字符串,对于每一个字符串求以这个字符串为后缀的字符串中第k小的编号 首先将字符串反转 那么就变成了对于每一个字符串求以这个字符串为前缀的字符串中第k小的编号 然后考虑对字符串排序 那 ...
- 性能测试实战-XYB项目-外网访问
压测业务选择 跟产品.开发负责人评估系统中需要压测的重要业务接口 考虑到考勤业务是每天老师都需要做的且可多次考勤,列入压测重要业务中 值日检查也是每天老师都需要操作的业务,最终选择了考勤业务及值日检查 ...
- 读写Word的组件DocX介绍与入门
本文为转载内容: 文章原地址:http://www.cnblogs.com/asxinyu/archive/2013/02/22/2921861.html 开源Word读写组件DocX介绍与入门 阅读 ...
- 创业公司十分钟简单搭建GIT私有库
欢迎关注老码农的微信公共账号,与CSDN博客同步 一.背景 小公司.协同开发的人不多,建gitlab比較麻烦,仅仅须要在Server端建立一个简单的git共享库就OK. 二.建立仓库 Server端: ...
- c++编译常见错误原因集中
1 c++ compiler error c4430 "c++ doesn't support default int" 1.1 可能的原因之一 我用了在一个头文件中定义的宏,但是 ...
- JMeter常用函数 使用图解
函数的调用都是以${__function()}这种形式开始的注意:“__”是两个英文下划线 __UUID 生成唯一字符串
- C 符号表导出
编译符号表导出示例: 使用GCC编译链接参数--version-script 控制动态符号表,如想 使用链接参数 --retain-symbols-file 控制静态符号表,--version-scr ...
- ALSA声卡驱动中的DAPM详解之六:精髓所在,牵一发而动全身
设计dapm的主要目的之一,就是希望声卡上的各种部件的电源按需分配,需要的就上电,不需要的就下电,使得整个音频系统总是处于最小的耗电状态,最主要的就是,这一切对用户空间的应用程序是透明的,也就是说,用 ...
- sql server中数据约束相关的查询
根据表名查找数据约束 SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'CMS_EventLog'; SEL ...