异步消息处理机制相关面试问题-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/ ...
随机推荐
- DRF视图-请求与响应
DRF视图 drf的代码简写除了在数据序列化体现以外,在视图中也是可以的.它在django原有的django.views.View类基础上,drf内部封装了许多子类以便我们使用. Django RES ...
- Linux中权限控制ACL命令
很多小伙伴觉得,Linux的权限管理命令不就是chown和chmod命令吗,什么时候有了ACL了? 什么是ACLACL是访问控制列表(Access Control List)的缩写,主要的目的是在提供 ...
- DP,数论————洛谷P4317 花神的数论题(求1~n二进制中1的个数和)
玄学代码(是洛谷题解里的一位dalao小粉兔写的) //数位DP(二进制)计算出f[i]为恰好有i个的方案数. //答案为∏(i^f[i]),快速幂解决. #include<bits/stdc+ ...
- mac docker --net=host
Docker 中的 host 模式指定是容器与主机享受相同的 network namespace. host 模式设计出来就是为了性能,但是这却对 docker 的隔离性造成了破坏,导致安全性降低. ...
- Flutter与Xamarin跨平台移动开发相比
在过去十年中,移动行业经历了巨大的增长,特别是在应用程序开发方面.据Statista报告称,全球智能手机用户超过20亿,预计到2022年底这一数字将增加到50亿以上.在这些智能手机中,近100%在三个 ...
- Linux下测试ZLAN 5800
今天师兄让帮忙测试ZLAN 5800八串口通信模块,windows下的测试按照手册来已经搞定,接下来是Linux下的测试. 因为厂家不提供Linux下的相关资料,所以需要在windows下设置好后直接 ...
- 【Python】【demo实验10】【练习实例】【打印斐波那契数列】
斐波那契数列介绍: 斐波那契数列(Fibonacci sequence),又称黄金分割数列.因数学家列昂纳多·斐波那契(Leonardoda Fibonacci)以兔子繁殖为例子而引入,故又称为“兔子 ...
- 第十三章 字符串 (四)之Scanner类
一.Scanner简述 Scanner扫描器类本质上是由正则表达式实现的,可以接受任何能产生数据的数据源对象,默认以空白符进行分词(包括\n等),使用各种next方法进行扫描匹配,获取匹配的数据. 二 ...
- BOF和EOF的详细解释 ADO的三个核心对象
使用ADO连接数据库进行查一个列表询的时候,数据库将查询结果返回查询端,在查询端的内存里面就会有一个列表,这个列表存放的就是查询的结果.这个内存中的列表就是数据集.在你的程序里面rs就是标识的这个数据 ...
- jmeter 工具学习 未完待续
about Apache JMeter是Apache组织的开源项目,是 一个纯Java桌面应用,用于压力测试和性能测试,它最初被设计用于 web应用测试,后来逐渐的扩展到其他领域 jmeter可以用于 ...