异步消息处理机制相关面试问题-intentservice面试问题详解
IntentService是什么?
IntentService是继承并处理异步请求的一个类,在IntentService内有一个工作线程来处理耗时操作,启动IntentService方法和启动传统的Service一样,同时,当任务执行完后,IntentService会自动停止,而不需要我们手动的stopSelf()。另外,可以启动IntentService多次,而每个耗时操作会以工作队列的方式在IntentService的onHandleIntent回调方法中执行,并且,每次只会执行一个线程,执行完第一个再执行第二个。
- 它本质上是一种特殊的Service,继承自Service并且本身是一个抽象类。
- 它内部是通过HandlerThread和Handler实现异步操作的。
IntentService使用方法:
关于它的使用可以参考之前写的博客:http://www.cnblogs.com/webor2006/p/4305715.html
下面总结一下:创建IntentService时,只需要实现onHandleIntent()和构造方法,onHandleIntent()为异步方法,可以执行耗时操作。
IntentService源码解析:
跟HandlerThread的源代码类似,代码也不多,如下:
public abstract class IntentService extends Service {
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private String mName;
private boolean mRedelivery;
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);
}
}
/**
* 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;
}
/**
* 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) {
mRedelivery = enabled;
}
@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);
}
@Override
public void onStart(@Nullable 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(@Nullable Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
@Override
public void onDestroy() {
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
@Nullable
public IBinder onBind(Intent intent) {
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)}.
* This may be null if the service is being restarted after
* its process has gone away; see
* {@link android.app.Service#onStartCommand}
* for details.
*/
@WorkerThread
protected abstract void onHandleIntent(@Nullable Intent intent);
}
而首先先看一下它的onCreate()方法:

首先会创建一个HandlerThread,然后再根据它的Looper来创建一个Handler,如下:


此时就可以在Handler中执行异步任务了。那IntentService是如何启动异步任务的呢?这里可以看一下onStrartCommand()方法:

又调用了onStart()方法:

接着就会到handler的handleMessage()方法中去处理了:

而onHandleIntent()方法是个抽象方法,由咱们自己来实现:

而其中调用停止任务时传了一个参数:

这时就会等待所有任务处理完之后才会停止,而不是立马停止。也就是如果有很多个任务都要由IntentService处理完之后,才会去让IntentService去停止,而非执行完一个就立马停止了。
它的本质就是一个封装了HandlerThread和handler的异步框架。
异步消息处理机制相关面试问题-intentservice面试问题详解的更多相关文章
- 异步消息处理机制相关面试问题-handlerThread面试问题详解
handlerThread产生背景: 开启Thread子线程进行耗时操作,多次创建和销毁线程是很耗系统资源的. handlerThread是什么? handler + thread + looper ...
- 异步消息处理机制相关面试问题-handler面试问题详解
什么是handler? 这个异常应该也就是引出handler的原因,也就是默认在非UI线程中是无法去更新UI的东东滴,那到底什么上handler呢? handler通过发送和处理Message和Run ...
- 异步消息处理机制相关面试问题-AsyncTask面试问题详解
什么是AsyncTask: 它本质上是一个封装了线程池和handler的异步框架. AsyncTask的使用方法: 三个参数: 五个方法: AsyncTask的内部原理: AsyncTask的注意事项 ...
- 【转】Android 异步消息处理机制 让你深入理解 Looper、Handler、Message三者关系
转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/38377229 ,本文出自[张鸿洋的博客] 很多人面试肯定都被问到过,请问Andr ...
- Android 异步消息处理机制 让你在深入了解 Looper、Handler、Message之间的关系
转载请注明出处:http://blog.csdn.net/lmj623565791/article/details/38377229 ,本文出自[张鸿洋的博客] 非常多人面试肯定都被问到过,请问And ...
- Android 异步消息处理机制 让你深入理解 Looper、Handler、Message三者关系
转自:http://blog.csdn.net/lmj623565791/article/details/38377229 ,本文出自[张鸿洋的博客] 很多人面试肯定都被问到过,请问Android中的 ...
- Android 异步消息处理机制终结篇 :深入理解 Looper、Handler、Message、MessageQueue四者关系
版权声明:本文出自汪磊的博客,转载请务必注明出处. 一.概述 我们知道更新UI操作我们需要在UI线程中操作,如果在子线程中更新UI会发生异常可能导致崩溃,但是在UI线程中进行耗时操作又会导致ANR,这 ...
- 【转载】Android异步消息处理机制详解及源码分析
PS一句:最终还是选择CSDN来整理发表这几年的知识点,该文章平行迁移到CSDN.因为CSDN也支持MarkDown语法了,牛逼啊! [工匠若水 http://blog.csdn.net/yanbob ...
- Android多线程----异步消息处理机制之Handler详解
[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/ ...
随机推荐
- ipmitool管理工具
一.ipmitool简介 IPMI(Intelligent Platform Management Interface)智能平台管理接口 1.IPMI的核心是一个专用芯片/控制器(叫做服务器处理器或基 ...
- MySQL_数据类型
目录 整型 浮点型 定点数类型 日期时间型 字符型 M为最大值,D为精度值 整型 数据类型 存储范围 字节 tinyint 有符号值:-128到127(-27到27-1) 无符号值:0到255(0到2 ...
- Linux文件权限基础知识
一.文件权限概述 Linux中每个文件或目录都有一组一组9个基础权限位,每三位字符被分为一组,他们分别是属主权限位(占三个字符).用户组权限位(占三个字符).其他用户权限位(占三个字符).比如rwxr ...
- 2019JAVA课程总结
课程总结 1.子类不能直接访问父类的私有属性,可通过get(),set()来间接访问. 2.super(),this()不可同时使用,因为其都必须放在首行,所以不可同时使用. 3.若删去super() ...
- Infix to Prefix conversion using two stacks
Infix : An expression is called the Infix expression if the operator appears in between the operands ...
- shell 字符
Shell 中的符号: 在shell中有很多符号代表了一些意思,重点说说 键盘上的符号在shell中的意义. 通配符: ~ 匹配家目录 ? 匹配单个字符.( ?之匹配单一的一个字符.x11 这种的就 ...
- python 基础(十九)--re正则表达式模块
正则表达式模式 模式 描述 ^ 匹配字符串的开头 $ 匹配字符串的末尾. . 匹配任意字符,除了换行符,当re.DOTALL标记被指定时,则可以匹配包括换行符的任意字符. [...] 用来表示一组字符 ...
- Hinton等人新研究:如何更好地测量神经网络表示相似性
Hinton等人新研究:如何更好地测量神经网络表示相似性 2019年05月22日 08:39:15 喜欢打酱油的老鸟 阅读数 177更多 分类专栏: 人工智能 https://www.toutia ...
- maven工程下整合spring+mybatis报Mapped Statements collection does not contain value for spring-mybatis-user-get错误
在整合spring+mybatis报了下面的错误: Mapped Statements collection does not contain value for spring-mybatis-use ...
- mybatis 延迟加载学习
一.什么是延迟加载 resultMap可实现高级映射(使用association.collection实现一对一及一对多映射),association.collection具备延迟加载功能. 需求: ...