IntentService
来源:互联网 发布:宋孝宗 知乎 编辑:程序博客网 时间:2024/05/27 20:51
首先列出Service存在的两个问题:
Service不会专门启动一个单独的进程,Service与它所在应用位于同一个进程中。
Service不是一条新的线程,因此不应该在Service中直接处理耗时的任务,否则很容易出现ANR(Application Not Responding)的情况。
所以这时候就需要用到Android多线程技术了,我们应该在Service的每个具体方法里开启一个子线程,然后在这里去处理那些耗时的逻辑。
但是这样的服务一旦启动之后就会一直处于运行状态,必须调用stopService()或者stopSelf()方法才能让服务停下来,于是Android提供了一个更好的方法。
IntentService类
ItentService将会使用队列来管理请求Intent,每当客户端代码通过Intent请求启动IntentService时,IntentService会将该Intent加入队列中,然后开启一条新的worker线程来处理该Intent。
对于异步的startService()请求,IntentService会按次序依次处理队列中的Intent,该线程保证同一时刻只处理一个Intent。由于它使用新的worker线程处理Intent请求,因此IntentService不会阻塞主线程,所以IntentService自己就可以处理耗时任务。
归纳一下就是:
IntentService会创建单独的worker线程来处理所有的Intent请求。
IntentService会创建单独的worker线程来处理onHandleIntent()方法实现的代码,因此开发者不需要处理多线程问题。
当所有请求处理完成后,IntentService会自动停止,因此开发者也无需调用stopSelf()方法来停止该Service。
为Service的onBind()方法提供了默认实现,默认实现的onBind()方法返回null。
为Service的onStartCommand()方法提供了默认实现,该实现会将请求Intent添加到队列中。
那么,扩展IntentService实现Service并不需要重写onBind()、onStartCommand()方法,只需要重写onHandleIntent()方法即可。
那么到底应该怎么做呢?小实现一下:
public class Demo extends IntentService{ public Demo(){ super("Demo"); //调用父类的有参构造函数() } @Override protected void onHandleIntent(Intent intent){ //在这里处理一些具体逻辑,不用担心ANR的问题,因为该方法是在子线程中运行的 ……………… } @Override public void onDestroy(){ super.onDestroy(); Log.d("Demo","onDestroy 已执行"); //因为IntentService在所有请求处理完成后会自动停止,所以这里重写了onDestroy()方法 }}
接着我们只需要在其他访问者比如activity上某个按钮的点击事件里写上下面两行代码即可
Intent intentService = new Intent(this,Demo.class);startService(intentService);
注:知识点参考自Android官方文档,《第一行代码》| 郭霖及《疯狂Android讲义》| 李刚
- IntentService
- IntentService
- intentservice
- IntentService
- IntentService
- IntentService
- IntentService
- IntentService
- IntentService
- IntentService
- IntentService
- IntentService
- IntentService
- IntentService
- IntentService
- IntentService
- IntentService
- intentservice
- Swift(十三、继承)
- linux 编译c程序与动态链接库
- 四大湖(C程序设计进阶第2周)
- ios数据解析
- 用Gparted调整ubuntu磁盘分区
- IntentService
- Bag of Features 方法
- nyoj62笨小熊
- 数据结构实验之栈六:下一较大值(二)
- 快速幂取模运算(Modular Exponentiation)
- ubuntu10.4NFS挂载到mini2440相关问题
- Hive安装及使用攻略
- 欢迎使用CSDN-markdown编辑器
- 数据结构实验之栈七:出栈序列判定