源码学习之IntenteService
2016-05-15 16:52
309 查看
IntentService是基于Service实现的,它会按需求处理一些异步任务。通过调用startService,客户端就可以发送请求了。如果有需要的话,Service才会被启动,在子线程依次处理每个Intent,处理完任务以后Service会停止。使用的时候要继承IntentService,并实现onHandleIntent(Intent intent)方法。IntentService会接收Intent,开启一个子线程,并在适当的时候停止Service。所有的请求会在一个单线程进行处理,所以在同一时刻只能处理一个任务。
调用onCreate以后,会启动一个工作线程(HandlerThread是继承Thread的),并初始化处理消息的ServiceHandler,和工作线程的Looper进行关联。 @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); }
调用这个方法以后,会给mServiceHandler发送一条消息,任务交由mServiceHandler来处理。 @Override public void onStart(Intent intent, int startId) { Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; msg.obj = intent; mServiceHandler.sendMessage(msg); }
收到消息以后,会调用onHandleIntent方法,在这个方法里可以实现自己的逻辑处理。当处理完所有消息以后,会调用stopSelf来停止Service。 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); } }
相关文章推荐
- VI编辑器之删除操作
- Linux下ln命令使用
- c#页面传参
- 2016华中农业大学预赛 E 想法题
- 通过eclipse创建maven项目
- NodeJS学习
- 37. Sudoku Solver
- 在Android Studio中进行单元测试和UI
- Python Tricks(一)—— np.where 与最大最小截断
- TensorFlow简介
- 构建账户系统
- C++ 11(八)
- Android源代码分析要看的书
- Java 关键点整理一
- linux企业常用服务---nfs
- poj之旅——1862
- 【MyBatis框架点滴】——初识+环境搭建
- Block究竟在哪
- Astar2016-Round1 Problem B(大数加、乘、除+斐波那契数列)
- UVA 1587 Box 【ACM/ICPC NEERC 2004】