1.IntentService 是什么

  1. 一个封装了HandlerThread和Handler的异步框架。
  2. 是一种特殊Service,继承自Service,是抽象类,必须创建子类才可以使用。
  3. 可用于执行后台耗时的任务,任务执行后会自动停止
  4. 具有高优先级(服务的原因),优先级比单纯的线程高很多,适合高优先级的后台任务,且不容易被系统杀死。
  5. 启动方式和Service一样。
  6. 可以多次启动,每个耗时操作都会以工作队列的方式在IntentService的onHandleIntent回调方法中执行。
  7. 串行执行。

2. IntentService的执行方式是串行还是并行

  串行

3. IntentService可以执行大量的耗时操作?

  1. 如果只有一个任务,是可以进行耗时操作的。
  2. 如果有很多任务,由于内部的HandlerThread是串行执行任务,会导致耗时操作阻塞了后续任务的执行。

4. IntentService和Service的区别

  1. 继承自Service
  2. IntentService任务执行完后会自动停止
  3. IntentService和Service优先级一致,比Thread高。
  4. Service处于主线程不能直接进行耗时操作; IntentService内部有HandlerThread,可以进行耗时操作。

5. IntentService的基本使用

1. 定义IntentService,实现onHandleIntent()'

public class LocalIntentService extends IntentService {
public static final String TAG="LocalIntentService";
public LocalIntentService( ) {
super(TAG);
} @Override
protected void onHandleIntent(Intent intent) {
String task=intent.getStringExtra("task");
Log.e(TAG, "onHandleIntent: task:"+task );
} @Override
public void onCreate() {
super.onCreate();
Log.e(TAG, "onCreate: " );
} @Override
public void onDestroy() {
super.onDestroy();
Log.e(TAG, "onDestroy: " );
}
}

  2.AndroidMainfest.xml 中声明ItnentService

<service android:name=".LocalIntentService"/>

  3. 开启IntentService

 findViewById(R.id.bt1).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent service=new Intent(MainActivity.this,LocalIntentService.class);
service.putExtra("task","task1");
startService(service); service.putExtra("task","task2");
startService(service); service.putExtra("task","task3");
startService(service); service.putExtra("task","task4");
startService(service); }
});

  

日志:

6. 源码和原理机制

1.IntetntService的OnCreate底层原理

  1. 构造了HandlerThread
  2. 并在每部保存了HandlerThread的Looper
  3. 并且使用该Looper创建了ServiceHandler
        //IntentService第一次启动调用
public void onCreate() {
super.onCreate();
//1. 创建一个HanlderThread
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
//2. 通过HanlderThread的Looper来构建Handler对象mServiceHandler
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);

2. IntentService的ServiceHandler

  1. HandlerThread会串行的取出任务并且执行,会调用ServiceHandler的handleMessage去处理任务。
  2. handlerMessage会去调用我们自定义的onHandleIntent
  3. 任务执行完毕后通过stopSelf(startId)停止Service。
  4. 任务结束后,在onDestory()中会退出HandlerThread中Looper的循环。

  

        //ServiceHandler接收并处理onStart()方法中发送的Msg
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
//1. 直接在onHandleIntent中处理(由子类实现)
onHandleIntent((Intent)msg.obj);
/**=================================================
* 2. 尝试停止服务(会等待所有消息都处理完毕后,才会停止)
* 不能采用stopSelf()——会立即停止服务
*================================================*/
stopSelf(msg.arg1); //会判断启动服务次数是否与startId相等
}
} public void onDestroy() {
mServiceLooper.quit();
}//销毁时会停止looper

  

3. IntentService内部去停止Service为什么不直接采用stopSelf()

  1. 采用stopSelf()——会立即停止服务
  2. 采用stopSelf(startId),会等所有消息全部处理完毕后,才会停止。会判断启动服务次数是否与startId相等

4. IntentService是如何停止HandlerThread的Looper消息循环的?

  1. 调用stopSelf(startId)后。
  2. 任务全部执行完,会停止服务,并且回调onDestory()。调用Looper的quit()方法即可

5. IntentService 多次startService会多次回调onHandleIntent()的内部流程?

  1. startService()->onStartCommand()->onStart()
  2. 通过HandlerThread的handler去发送消息。
  3. HandlerThread在处理任务时,会去调用onHandleIntent方法。
public abstract class IntentService extends Service {
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
...省略... //IntentService每次启动都会调用
public int onStartCommand(Intent intent, int flags, int startId) {
//3. 直接调用onStart
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
public void onStart(Intent intent, int startId) {
//4. 通过mServiceHandler发送一个消息(该消息会在HanlderThread中处理)
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
//2. 该Intent与startService(intent)中的Intent完全一致
protected abstract void onHandleIntent(Intent intent); }

  

6. IntentService的源码总结:

  1. IntentService通过发送消息的方式向HandlerThread请求执行任务
  2. HandlerThread中的looper是顺序处理消息,因此有多个后台任务时,都会按照外界发起的顺序排队执行
  3. 启动流程:onCreate()->onStartCommand()->onStart()
  4. 消息处理流程:ServiceHandler.handleMessage()->onHandleIntent()

参考:

IntentService详解

IntentService介绍的更多相关文章

  1. 【转载】Android IntentService使用全面介绍及源码解析

    一 IntentService介绍 IntentService定义的三个基本点:是什么?怎么用?如何work? 官方解释如下: //IntentService定义的三个基本点:是什么?怎么用?如何wo ...

  2. Android Service总结05 之IntentService

    Android Service总结05 之IntentService   版本 版本说明 发布时间 发布人 V1.0 添加了IntentService的介绍和示例 2013-03-17 Skywang ...

  3. Android Service详解

    service作为四大组件值得我们的更多的关注 在Android中,Activity主要负责前台页面的展示,Service主要负责需要长期运行的任务.例如,一个从service播放音乐的音乐播放器,应 ...

  4. Android Service总结03 之被启动的服务 -- Started Service

    Android Service总结03 之被启动的服务 -- Started Service 版本 版本说明 发布时间 发布人 V1.0 添加了Service的介绍和示例 2013-03-17 Sky ...

  5. Android IntentService使用介绍以及源码解析

    版权声明:本文出自汪磊的博客,转载请务必注明出处. 一.IntentService概述及使用举例 IntentService内部实现机制用到了HandlerThread,如果对HandlerThrea ...

  6. Android中的IntentService

    首先说下,其他概念:Android中的本地服务与远程服务是什么? 本地服务:LocalService 应用程序内部------startService远程服务:RemoteService androi ...

  7. Android之Notification介绍

    Notification就是在桌面的状态通知栏.这主要涉及三个主要类: Notification:设置通知的各个属性. NotificationManager:负责发送通知和取消通知 Notifica ...

  8. IntentService源码分析

    和HandlerThread一样,IntentService也是Android替我们封装的一个Helper类,用来简化开发流程的.接下来分析源码的时候 你就明白是怎么回事了.IntentService ...

  9. 【Android】IntentService & HandlerThread源码解析

    一.前言 在学习Service的时候,我们一定会知道IntentService:官方文档不止一次强调,Service本身是运行在主线程中的(详见:[Android]Service),而主线程中是不适合 ...

随机推荐

  1. SQL 知识及用法备忘录

    ---查询当前数据库一共有多少张表 ) from sysobjects where xtype='U' ---查询当前数据库有多少张视图 ) from sysobjects where xtype=' ...

  2. bzoj4542 大数

    Description 小 B 有一个很大的数 S,长度达到了 N 位:这个数可以看成是一个串,它可能有前导 0,例如00009312345.小B还有一个素数P.现在,小 B 提出了 M 个询问,每个 ...

  3. 利用spring的ApplicationListener实现springmvc容器的初始化加载

    1.我们在使用springmvc进行配置的时候一般初始化都是在web.xml里面进行的,但是自己在使用的时候经常会测试一些数据,这样就只有加载spring-mvc.xml的配置文件来实现.为了更方便的 ...

  4. 补充: istio安装

    首先有一个概念: CRD - Custom Resource Definitions: CRDS文件: install/kubernetes/helm/istio/templates/crds.yml ...

  5. Mathtype 公式显示方框

    公式编辑器mathtype中一些符号显示方框,如何解决呢?出现这个问题的原因是这是因为windows中的mtextra.ttf(显示为MT Extra (TrueType))字体文件不存在或版本太低, ...

  6. GridEh Lookup

    Flexible adjustment of a lookup inplace editor 没有输入拼音码搜索功能. Drop-Down Forms 这个比较符合中国人的习惯,搜索框,不错,点下来箭 ...

  7. Yii框架操作数据库的几种方式与mysql_escape_string

    一.Yii操作数据库的几种选择 1,PDO方式. $sql = "";//原生态sql语句 xx::model()->dbConnection->createComma ...

  8. (转 留存)Windows环境下的NodeJS+NPM+GIT+Bower安装配置步骤

    Windows环境下的NodeJS+NPM+GIT+Bower安装配置步骤 标签: NodeJSnpmbower 2015-07-17 16:38 3016人阅读 评论(0) 收藏 举报  分类: G ...

  9. GBDT,Adaboosting概念区分 GBDT与xgboost区别

    http://blog.csdn.net/w28971023/article/details/8240756 ============================================= ...

  10. Python列表练习题

    1.创建一个空列表,命名为names,往里面添加 Lihua.Rain.Jack.Xiuxiu.Peiqi和Black元素. #!-*- coding:utf-8 -*- names = [" ...