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 ...
随机推荐
- ExtJs--09--javascript对象的方法的3种写法 prototype通过原型设置方法效率最好
/** * javascript对象的方法的3种写法 推荐第三种 运行效率最好 */ function P(name , age){ this.name = name ; this.age = age ...
- Windows 文件夹修改为exe的原理和解决办法
有关文件夹后缀改为exe的病毒 该病毒之前出现过,不过没多长时间便消失了,最新的这个应该是变种,下面解决一下该病毒在移动存储设备中的问题: 该病毒并不具备能够将文件夹改为文件的能力,只是将原有文件夹全 ...
- C#文件运行类的VB.NET版本号
主要差别在于事件处理要採用AddHandler和RemoveHandler,以及AddressOf三个keyword,其他基本一样. VB的操作稍微繁琐.但仍然能够实现.
- 王立平--SQLite,SQLiteOpenHelper的简单应用
Android平台提供给我们一个数据库辅助类来创建或打开数据库,这个辅助类继承自SQLiteOpenHelper类.在该类的构造器中,调用Context中的方法创建并打开一个指定名称的数据库对象.继承 ...
- 苹果官方Instruments工具之Automation的介绍
instruments中国的工具測试有非常多,包含非常多方面.eg:内存泄露的測试.网络连接.和cpu内存的使用情况一系列数据的图形界面的显示. 功能的介绍能够看以下的截图图片: watermark/ ...
- Bitmap通过getWidth和getHeight获取尺寸不符
在使用BitmapFactory载入图片时,常会出现这样的情况,返回的图片尺寸与实际尺寸不符.这是因为我们把图片资源放到res/drawable文件路径下时,选择的文件不同所致.不同的目录会有不同的缩 ...
- 【bzoj1251】序列终结者(伸展树)
[bzoj1251]序列终结者(伸展树) Description 网上有许多题,就是给定一个序列,要你支持几种操作:A.B.C.D.一看另一道题,又是一个序列 要支持几种操作:D.C.B.A.尤其是我 ...
- bzoj 1022 小约翰的游戏John
题目大意: n堆石子,两个人轮流取石子,每个人取的时候,可以随意选择一堆石子 在这堆石子中取走任意多的石子,但不能一粒石子也不取,取到最后一粒石子的人算输 思路: 首先当每堆石子数都为1时,偶数为先手 ...
- php的session
来源:http://blog.163.com/lgh_2002/blog/static/4401752620105246517509/ http协议是WEB服务器与客户 端(浏览器)相互通信的协议,它 ...
- ckeditor详细设置
CKEditor 3 JavaScript API Documentation : http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.con ...