异步消息处理机制相关面试问题-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/ ...
随机推荐
- linux常用命令---------------find
1.find 基本模式 find path -option [ -print ] [ -exec -ok command ] {} \; 2.常用的参数 -name name, -iname name ...
- [转帖]nginx 80端口重定向 转发到443端口
nginx 80端口重定向到443端口 2017年05月16日 13:53:58 幸福丶如此 阅读数 33387 版权声明:本文为博主原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文 ...
- Redis(1.4)Redis的持久化
Redis持久化 [1]概念 Redis所有的数据存储在内存中,为了保证重启后,redis数据不丢失,需要把redis数据保存在磁盘中. [2]持久化使用方式策略 (1)RDB 方式:默认支持,不需要 ...
- [转帖]postgres 创建新用户并授权-- 非常好的
postgres 创建新用户并授权 https://blog.csdn.net/XuHang666/article/details/81506297 原作者总结的挺好的 可以用来学习一下. grant ...
- [转帖]盖茨辉煌后将归隐 DOS之父仍为生计打拼(图)
盖茨辉煌后将归隐 DOS之父仍为生计打拼(图) http://www.sina.com.cn 2007年12月10日 09:43 新浪科技 https://tech.sina.com.cn/it/2 ...
- MySQL优化心得
一打开科技类论坛,最常看到的文章主题就是MySQL性能优化了,为什么要优化呢? 因为: 数据库出现瓶颈,系统的吞吐量出现访问速度慢 随着应用程序的运行,数据库的中的数据会越来越多,处理时间变长 数据读 ...
- 小记--------SparkContext初始化原理机制图解
- AMD平台如何使用Android Studio官方的高性能模拟器
当我第一次接触Android Studio的时候,脑子里第一个想法是:tm不就是IDEA么??以为自己会用的贼六,结果其他小朋友的模拟器都打开了,才发现自己运行不了模拟器.一度以为是我哪里操作错了.于 ...
- 简易计算器-leetcode
今天,开始在leetcode上面开始做题,第一个题目是: Implement a basic calculator to evaluate a simple expression string. Th ...
- X86逆向15:OD脚本的编写技巧
本章节我们将学习OD脚本的使用与编写技巧,脚本有啥用呢?脚本的用处非常的大,比如我们要对按钮事件进行批量下断点,此时使用自动化脚本将大大减小我们的工作量,再比如有些比较简单的压缩壳需要脱壳,此时我们也 ...