Handler是整个消息系统的核心,是Handler向MessageQueue发送的Message,最后Looper也是把消息通知给Handler,所以就从Handler讲起。

一、Handler

Handler的构造函数有很多,但本质差不多:

public Handler() {
this(null, false);
}

  

public Handler(Callback callback, boolean async) {
//自动绑定当前线程的looper
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");//从这可以看出,创建Handler必须有Looper
}
mQueue = mLooper.mQueue; //Looper的MessageQueue
mCallback = callback; //一个回掉接口
mAsynchronous = async;
}

这个是创建给定Looper的Handler  :

public Handler(Looper looper, Callback callback, boolean async) {    
       mLooper = looper;  
       mQueue = looper.mQueue;  
       mCallback = callback;  
       mAsynchronous = async;  
   }

二、Looper的源代码:

public static Looper myLooper() {
return sThreadLocal.get();
}

  在一个子线程中创建Looper的一般步骤:(这是我自己写的,不是源代码)

class MyThread extends Thread{
public Handler handler;
public Looper looper;
public void run() {
Looper.prepare();//创建一个looper
looper = Looper.myLooper();
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
System.out.println("currentThread->"+Thread.currentThread());
}
};
Looper.loop();//让消息循环起来
}
}

  下面就看看Looper.prepare,Looper.loop方法:

public static void prepare() {
prepare(true);
} private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {//sThreadLocal使得线程能够保持各自独立的一个对象。
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}

  Looper.prepare():

public static void loop() {
final Looper me = myLooper();
if (me == null) { //如果Looper为空
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue; 。。。。
for (;;) {
Message msg = queue.next(); // 循环下一个
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
} 。。。。 msg.target.dispatchMessage(msg); //分发消息,msg.target就是Handler if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
。。。。 msg.recycle(); //回收msg到msgPool
}
}

  从这些代码可以看出Looper不断检查MessagePool是否有《==Message,有的话就通过Handler的dispatchMessage(msg)发送出去,利用Handler与外界交互。

3.Message的源代码:

public static Message obtain() {   //得到Message对象
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
sPoolSize--;
return m;
}
}
return new Message(); //没有就新建
}

  handler.obtainMessage()方法:

public final Message obtainMessage()
{
return Message.obtain(this); //通过Message的obtain方法
}

  

public static Message obtain(Handler h) {  //就是这个方法
Message m = obtain(); //最终调用的还是obtain方法
m.target = h; //target是handler return m;
}

  看了上边的源代码,相信你一定对Handler,message,Looper有了一定了解,对编程中常遇到的方法,知道是怎么用的啦。其实学android一定要常看源码,源码很有用。

4.下边就是上代码,实例分析:

<pre name="code" class="java">package com.example.handler_01;  

import android.Manifest.permission;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast; public class MainActivity extends Activity implements OnClickListener{ private TextView textView;
private Button button; private Handler handler = new Handler(new Callback() {//拦截消息 public boolean handleMessage(Message msg) { //截获handler的发送的消息 Toast.makeText(getApplicationContext(), ""+1, 1).show();
//return false;
return false;//若返回true,则证明截获,下面的handleMessage就不会执行!
}
}){
public void handleMessage(Message msg) {
Toast.makeText(getApplicationContext(), ""+2, 1).show();
Person person = (Person)msg.obj;
System.out.println(person.toString());
}
}; private MyRunnable myRunnable=new MyRunnable(); private ImageView imageView; private int images[]={R.drawable.a1,R.drawable.a2,R.drawable.a3};
private int index; class MyRunnable implements Runnable{ //不断的更新图片,3张轮换 @Override
public void run() {
index++;
index=index%3; //不断循环
imageView.setImageResource(images[index]);
handler.postDelayed(myRunnable, 1000); //每隔一段时间执行myRunnable
System.out.println("MyRunnable中的线程:"+Thread.currentThread());//运行在当前主线程!
} }
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textview);
imageView = (ImageView) findViewById(R.id.imageView1);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(this);
new Thread(){
@Override
public void run() {
try {
Thread.sleep(2000);
/*Message message = new Message();
message.arg1=88;*/
Message message = handler.obtainMessage(); Person person = new Person();
person.age=20;
person.name="chaochao";
message.obj=person;
handler.sendMessage(message);//在子线程中向主线程发消息。
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
}.start();
handler.postDelayed(myRunnable, 1000);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
handler.removeCallbacks(myRunnable);
//handler.sendEmptyMessage(1);
break; default:
break;
} } class Person{
public int age;
public String name; public String toString() {
return "name="+name+" age="+age;
}
}
}

  布局很简单,就不上代码啦。

运行结果:

图片自己可以随便能一个。。。。

在后边再详细解析Handler的用法。。

转发请注明出处:http://www.cnblogs.com/jycboy/p/handlerjx.html

结合源代码详解android消息模型的更多相关文章

  1. 图文详解 Android Binder跨进程通信机制 原理

    图文详解 Android Binder跨进程通信机制 原理 目录 目录 1. Binder到底是什么? 中文即 粘合剂,意思为粘合了两个不同的进程 网上有很多对Binder的定义,但都说不清楚:Bin ...

  2. 详解Android首选项框架ListPreference

    详解Android首选项框架ListPreference 原文地址 探索首选项框架 在深入探讨Android的首选项框架之前,首先构想一个需要使用首选项的场景,然后分析如何实现这一场景.假设你正在编写 ...

  3. 详解android:scaleType属性

    详解android:scaleType属性 转自:http://blog.csdn.net/encienqi/article/details/7913262    http://juliaailse. ...

  4. adb shell 命令详解,android

    http://www.miui.com/article-275-1.html http://noobjava.iteye.com/blog/1914348 adb shell 命令详解,android ...

  5. 详解Android Activity---启动模式

    相关的基本概念: 1.任务栈(Task)   若干个Activity的集合的栈表示一个Task.   栈不仅仅只包含自身程序的Activity,它也可以跨应用包含其他应用的Activity,这样有利于 ...

  6. Android Binder IPC详解-Android学习之旅(96)

    linux内存空间与BInder Driver Android进程和linux进程一样,他们只运行在进程固有的虚拟空间中.一个4GB的虚拟地址空间,其中3GB是用户空间,1GB是内核空间 ,用户空间是 ...

  7. 详解Android中的四大组件之一:Activity详解

    activity的生命周期 activity的四种状态 running:正在运行,处于活动状态,用户可以点击屏幕,是将activity处于栈顶的状态. paused:暂停,处于失去焦点的时候,处于pa ...

  8. adb shell 命令详解,android, adb logcat

    http://www.miui.com/article-275-1.html http://noobjava.iteye.com/blog/1914348 adb shell 命令详解,android ...

  9. [转]Hadoop集群_WordCount运行详解--MapReduce编程模型

    Hadoop集群_WordCount运行详解--MapReduce编程模型 下面这篇文章写得非常好,有利于初学mapreduce的入门 http://www.nosqldb.cn/1369099810 ...

随机推荐

  1. WPA字典锦集

    1.xiemimendictionary 字典下载(第二季),500W整理过后还有282W条不重复的密码 字典下载,600W整理过后还有400W条不重复的密码 历次泄+常用弱口令字典集合[无中文去重复 ...

  2. 【原创】MYSQL++源码剖析——前言与目录

    终于完成了! 从第一次想写到现在真的写好大概花了我3个月时间.原来一直读人家的系列文章,总感慨作者的用心良苦和无私奉献,自己在心里总是会觉得有那么些冲动也来写一个. 最开始的麻烦是犹豫该选哪个主题.其 ...

  3. Java 集合系列14之 Map总结(HashMap, Hashtable, TreeMap, WeakHashMap等使用场景)

    概要 学完了Map的全部内容,我们再回头开开Map的框架图. 本章内容包括:第1部分 Map概括第2部分 HashMap和Hashtable异同第3部分 HashMap和WeakHashMap异同 转 ...

  4. [Design Patterns] 4. Creation Pattern

    设计模式是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结,使用设计模式的目的是提高代码的可重用性,让代码更容易被他人理解,并保证代码可靠性.它是代码编制真正实现工程化. 四个关键元素 ...

  5. Bucky – 免费开源的实时用户监控工具

    Bucky 是一个开源的实时用户监控工具,用于衡量用户在浏览器中使用 Web 应用程序时的性能.它可以自动测量你的网页需要多长时间来加载,Ajax 请求需要多长时间和各个函数需要实行多久. 您可能感兴 ...

  6. 使用 Web Tracing Framework 分析富 JS 应用的性能

    来自谷歌的 Web Tracing Framework 包含一组工具和脚本,用于 JavaScript 相关代码的性能分析.它是重 JavaScript 应用程序的理想选择,而 JavaScript ...

  7. Spring应用教程-1

    作者:禅楼望月(http://www.cnblogs.com/yaoyinglong) Spring是Web框架,是容器框架,用于配置bean,并维护bean之间的关系的框架. 1. Spring在整 ...

  8. 利用 ELK系统分析Nginx日志并对数据进行可视化展示

    一.写在前面 结合之前写的一篇文章:Centos7 之安装Logstash ELK stack 日志管理系统,上篇文章主要讲了监控软件的作用以及部署方法.而这篇文章介绍的是单独监控nginx 日志分析 ...

  9. MySQL多实例,主从同步

    由于背景原因,所做的主从同步还是要基于MySQL 5.1的版本,主从同步主要是一个数据库读写访问原来的数据库热度过大,需要做到使用从库对读分压. MySQL主从同步介绍     MySQL 支持单双向 ...

  10. Node.js爬虫数据抓取乱码问题总结

    一.非UTF-8页面处理 1.背景 windows-1251编码 比如俄语网站:https://vk.com/cciinniikk 可耻地发现是这种编码 所有这里主要说的是 Windows-1251( ...