文章讲述Looper/MessageQueue/Handler/HandlerThread相关的技能和使用方法.

什么是Looper?Looper有什么作用?

Looper是用于给线程(Thread)添加消息队列(MessageQueue)的工具;让消息队列的处理处于循环状态,一旦接收到消息,会唤醒线程并执行消息处理方法.

通常情况下,Activity和Service等系统组件不会使用到Looper,Framework层已经为其初始化好了线程(附带有消息队列,称为主线程或UI线程);主线程会一直运行,处理用户事件.

如果我们需要新建一个线程,且这个线程要能够循环处理其他线程发过来的消息事件,或者需要长时间与其他线程进行交互,这时就需要使用到Looper给线程建立消息队列.

Looper怎么用?

Looper类中以下方法:

比较常用的是以下方法:

public static void prepare();
public static Looper myLooper();
public static void loop();
public void quit();

方法描述:

1. prepare():在线程run()最开始,调用该方法;为线程初始化消息队列.

2. myLooper():获取Looper对象引用;一定要在prepare()之后调用.

3. loop():让线程的消息队列开始运行,接收消息;

4. quit():退出消息循环.若线程中无其他操作,线程将终止运行.

    public class WorkThread extends Thread {
// 工作线程的Handler实例
private Handler mHandler;
// 工作线程的Looper实例
private Looper mLooper;
public WorkThread() {
LogUtil.d(TAG, "WorkThread::starting...");
start();
}
public void run() {
LogUtil.d(TAG, "WorkThread::runningF...");
// 初始化消息队列
Looper.prepare();
// 获取Looper对象
mLooper = Looper.myLooper();
// 在工作线程创建Handler
mHandler = new Handler(mLooper) {
@Override
public void handleMessage(android.os.Message msg) {
LogUtil.d(TAG, "handleMessage::starting...");
StringBuilder sb = new StringBuilder();
sb.append("it is my please to serve you, please be patient to wait!\n");
// 子线程一直在循环执行
for (int i = 0; i < 100; i++) {
sb.append(".");
Message newMsg = Message.obtain();
newMsg.obj = sb.toString();
mMainHanlder.sendMessage(newMsg);
SystemClock.sleep(1000);
}
sb.append("\nyour work is done");
Message otherMsg = Message.obtain();
otherMsg.obj = sb.toString();
mMainHanlder.sendMessage(otherMsg);
};
};
// 开始接收消息
Looper.loop();
}
public void exit() {
LogUtil.d(TAG, "exit::starting...");
if (mLooper != null) {
// 退出消息循环
mLooper.quit();
mLooper = null;
LogUtil.d(TAG, "exit::mLooper is set to null");
}
}
public void executeTask(String txt) {
LogUtil.d(TAG, "executeTask::starting...");
if (mLooper == null || mHandler == null) {
LogUtil.d(TAG, "executeTask::mLooper is null");
Message msg = Message.obtain();
msg.obj = "Sorry man, it is out of service";
// 使用主线程的Handler实例,向主线程发送Message
mMainHanlder.sendMessage(msg);
return;
}
LogUtil.d(TAG, "executeTask::mLooper is not null");
Message msg = Message.obtain();
msg.obj = txt;
mHandler.sendMessage(msg);
}
}

在工作线程中创建的Handler是属于该子线程(工作线程)的,而不是主线程.

疑惑:

Thread的状态和Looper的关系:未退出消息循环时,Thread是不会死亡的;一旦消息队列接收到消息,则会唤醒线程并处理消息.

何时退出Thread?如上述所说,若没有消息队列,一旦run()执行结束,该Thread也就是结束.

Handler是用于操作线程内部消息队列的类.即是用Handler来操作消息队列.如:给消息队列发送消息,和从消息队列中取出消息并处理.Handler作用:用于线程内部消息处理;用于线程间通讯(ITC-Inter Thread Communication).

必须要指出的是,此处的Handler来自于:import android.os.Handler;

Handler用于线程内部消息处理,即在将来定时执行某个动作,或者周期性执行动作.Handler用于操作线程内部的消息队列,可以用来线程间通信ITC,大大减少同步的烦恼,甚至不需要使用synchronized.

Handler/Looper/MessageQueue是属于一个线程内部的数据,但提供给外部线程访问的接口,Handler就是公开给外部线程,与线程通讯的接口.MessageQueue是相对较底层的,较少直接使用;Looper和Handler就是专门用来操作底层MessageQueue的.

Handler是用于操作一个线程内部的消息队列的,所以Handler必须依附于一个线程,而且只能是一个线程.也就是说:必须在一个线程内创建Handler,同时制定Handler的回调方法handlerMessage(Message msg).

以上方法都是设置定时器,在指定的时间向Handler所在的MessageQueue发送消息.线程内部消息循环并不是并发处理(并非创建一个线程),而是在同一个线程中处理.

并发执行或处理,既是多线程执行.

正确创建Handler,需要让Handler与线程绑定.如果给Handler指定Looper对象,此时Handler便绑定到Looper对象所在的线程.Handler的消息处理回调方法会在这个线程执行;如果不指定Looper,则Handler绑定到创建此Handler的线程内,消息处理回调方法也在这个线程执行.

如果要在一个线程中使用消息队列和Handler,Android API中有已经封装好的HanlderThread,在这个类中已经做好了Looper的初始化工作.

    private void initBackThread() {
mIndexUpdateThread = new HandlerThread("check-message-coming");
mIndexUpdateThread.start();
// 使用mIndexUpdateThread创建Handler实例,即这个Handler就在mIndexUpdateThread线程中
mIndexUpdateHandler = new Handler(mIndexUpdateThread.getLooper()) {
@Override
public void handleMessage(android.os.Message msg) {
int what = msg.what;
LogUtil.d(TAG, "handleMessage::msg.what=" + what
+ "; Thread name=" + Thread.currentThread().getName());
checkforUpdate();
if (mIsUpdateInfo) {
// 实现循环更新
mIndexUpdateHandler.sendEmptyMessageDelayed(
MSG_UPDATE_INFO, 500);
}
};
};
}

Handler Looper 解析的更多相关文章

  1. Android之消息机制Handler,Looper,Message解析

    PS:由于感冒原因,本篇写的有点没有主干,大家凑合看吧.. 学习内容: 1.MessageQueue,Looper,MessageQueue的作用. 2.子线程向主线程中发送消息 3.主线程向子线程中 ...

  2. Handler Looper源码解析(Android消息传递机制)

    Android的Handler类应该是常用到的,多用于线程间的通信,以及子线程发送消息通知UI线程刷新View等等.这里我主要总结下我对整个消息传递机制,包括Handler,Looper,Messag ...

  3. handler looper和messageQueue

    一.用法. Looper为了应付新闻周期,在创建过程中初始化MessageQueue. Handler在一个消息到当前线程的其他线程 MessageQueue用于存储所述消息 Looper其中线程创建 ...

  4. Handler+Looper+MessageQueue深入详解

    概述:Android中的异步处理机制由四部分组成:Handler+Looper+MessageQueue+message,用于实现线程间的通信. 用到的概念: Handler: 主要作用是发送消息和处 ...

  5. 讲讲Handler+Looper+MessageQueue 关系

    Handler+Looper+MessageQueue这三者的关系其实就是Android的消息机制.这块内容相比开发人员都不陌生,在面试中,或者日常开发中都会碰到,今天就来讲这三者的关系. 概述: H ...

  6. Android的消息机制: Message/MessageQueue/Handler/Looper

    概览   * Message:消息.消息里面可包含简单数据.Object和Bundle,还可以包含一个Runnable(实际上可看做回调). * MessageQueue:消息队列,供Looper线程 ...

  7. Handler一定要在主线程实例化吗?new Handler()和new Handler(Looper.getMainLooper())的区别?

    一个帖子的整理: Handler一定要在主线程实例化吗?new Handler()和new Handler(Looper.getMainLooper())的区别如果你不带参数的实例化:Handler ...

  8. new Handler()和new Handler(Looper.getMainLooper())的区别

    一个帖子的整理: Handler一定要在主线程实例化吗?new Handler()和new Handler(Looper.getMainLooper())的区别如果你不带参数的实例化:Handler ...

  9. Handler,Looper,MessageQueue流程梳理

    目的:handle的出现主要是为了解决线程间通讯. 举个例子,android是不允许在主线程中访问网络,因为这样会阻塞主线程,影响性能,所以访问网络都是放在子线程中执行,对于网络返回的结果则需要显示在 ...

随机推荐

  1. django-url的分发

    1)url的分发: 1,首先在全局的url里面的路径中写好,你要分发的路径名. 2,并且在你要分发的路径下,创好新的url文件. 在分发的路径名里面,把全局url里面的代码,复制过来 3,最后在浏览器 ...

  2. 关于百度地图(离线)使用过程报“Cannot read property 'jb' of undefined ”错误的解决办法

    使用百度地图(离线)API时,地图无法显示,f12查看报错: BaiduApi_2.0.js:1056 Uncaught TypeError: Cannot read property 'jb' of ...

  3. 海亮OI学习游记

    这只是一篇纯洁的游记,这里将要记录我在海亮十天集训的生活与被虐的历史QWQ...... Day1(2.10)刚来到海亮,嗯,这的环境真的不错. 来到机房,woc这机房的配置好高啊...这里都能打守望屁 ...

  4. 解决Java getResource 路径中含有中文的情况

    问题描述 当Java调用getResource方法,但是因为路径中含有中文时,得不到正确的路径 问题分析 编码转换问题 当我们使用ClassLoader的getResource方法获取路径时,获取到的 ...

  5. Client-Side Template Injection with AngularJS

    <html> <head> <meta charset="utf-8"> <script src="https://cdn.bo ...

  6. 微信获取企业token流程

    1.获取服务商Accesstoken(每10分钟企业微信会推送一次,两个小时后过期) 2.根据suitid.accesstoken.第三方企业corpid.第三方企业permanentcode,得到第 ...

  7. 针对主机CPU idle性能情况需求脚本编写

    [环境介绍] 系统环境:Linux + osw + python 2.7.10 [背景描述] 需求:当系统服务器出现性能告警的时候,需要定位具体的时间点来进行有针对性的去查询产生的问题.OSW提供了很 ...

  8. FineUIMvc 常见问题及解决办法

    Ø  简介 FineUIMvc 是基于 jQuery 的专业 ASP.NET MVC/Core 控件库,本文主要介绍 FineUIMvc 的常见问题及解决办法. 1.   View 中无法调用 Htm ...

  9. Pipeline load and load from git

    load https://www.sourcefield.nl/post/jenkins-pipeline-tutorial/ node { // Use the shell to create th ...

  10. spring+springMVC+mybatis简单整合

    spring+springMVC+mybatis简单整合, springMVC框架是spring的子项目,所以框架的整合方式为,spring+Mybatis或springMVC+mybatis. 三大 ...