最经面试中,技术面试中有一个是Handler的消息机制,细细想想,我经常用到的Handler无非是在主线程(或者说Activity)新建一个Handler对象,另外一个Thread是异步加载数据,同时当他加载完数据后就send到主线程中的那个Handler对象,接着Handler来处理,刚才发送的一些消息。

 public class HandlerTestActivity extends Activity {
private TextView tv;
private static final int UPDATE = 0;
private Handler handler = new Handler() { @Override
public void handleMessage(Message msg) {
// TODO 接收消息并且去更新UI线程上的控件内容
if (msg.what == UPDATE) {
// Bundle b = msg.getData();
// tv.setText(b.getString("num"));
tv.setText(String.valueOf(msg.obj));
}
super.handleMessage(msg);
}
}; /** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.tv); new Thread() {
@Override
public void run() {
// TODO 子线程中通过handler发送消息给handler接收,由handler去更新TextView的值
try {
for (int i = 0; i < 100; i++) {
Thread.sleep(500);
Message msg = new Message();
msg.what = UPDATE;
// Bundle b = new Bundle();
// b.putString("num", "更新后的值:" + i);
// msg.setData(b);
msg.obj = "更新后的值:" + i;
handler.sendMessage(msg);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
} }

如图所示,每个Thread都一个Looper,这个Looper类是用于管理其中的消息队列(MessageQueue)的,那Handler是干嘛的呢,他是用来传递消息队列的。

那下面就分析Looper、Hanlder方法吧。

Looper方法是用来处理消息队列的,注意了,它和线程是绑定的。

要是想在子线程中获取一个Looper该怎么做呢:

    Looper.prepare();
Looper looper = Looper.myLooper();

那么这些都干了哪些工作呢???

来看下它的源码吧:

Looper:

……
//准备Looper相关事宜
public static void prepare() {
//只能有一个对象哦
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper());
}
//构造函数
/*新建一个消息队列
* 把当前运行的线程作为运行线程
*/ private Looper() {
mQueue = new MessageQueue();
mRun = true;
mThread = Thread.currentThread();
}

public static final Looper myLooper() {

//这个方法是从当前线程的ThreadLocal中拿出设置的looper

return (Looper)sThreadLocal.get();

}

/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static void loop() {
Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
MessageQueue queue = me.mQueue; // Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity(); while (true) {
Message msg = queue.next(); // might block
if (msg != null) {
if (msg.target == null) {
// No target is a magic identifier for the quit message.
return;
} long wallStart = 0;
long threadStart = 0; // This must be in a local variable, in case a UI event sets the logger
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
wallStart = SystemClock.currentTimeMicro();
threadStart = SystemClock.currentThreadTimeMicro();
} msg.target.dispatchMessage(msg); if (logging != null) {
long wallTime = SystemClock.currentTimeMicro() - wallStart;
long threadTime = SystemClock.currentThreadTimeMicro() - threadStart; logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
if (logging instanceof Profiler) {
((Profiler) logging).profile(msg, wallStart, wallTime,
threadStart, threadTime);
}
} // Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "Thread identity changed from 0x"
+ Long.toHexString(ident) + " to 0x"
+ Long.toHexString(newIdent) + " while dispatching to "
+ msg.target.getClass().getName() + " "
+ msg.callback + " what=" + msg.what);
} msg.recycle();
}
}
}

下面就来看下Handler:

public Handler() {
if (FIND_POTENTIAL_LEAKS) {
final Class<? extends Handler> klass = getClass();
if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
(klass.getModifiers() & Modifier.STATIC) == 0) {
Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
klass.getCanonicalName());
}
}
//先获得一个Looper对象,这个要是在子线程里,是需要先prepare()的 mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = null;
}
/**
* Returns a new {@link android.os.Message Message} from the global message pool. More efficient than
* creating and allocating new instances. The retrieved message has its handler set to this instance (Message.target == this).
* If you don't want that facility, just call Message.obtain() instead.
会从消息池里面取得消息队列
*/
public final Message obtainMessage()
{
return Message.obtain(this);
}

那我现在写个小例子,是在子线程实现的消息的传递。

@Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.btn1) {
new Thread() { public void run() { Log.i("log", "run"); Looper.prepare();
// Looper looper = Looper.myLooper();
Toast.makeText(MainActivity.this, "toast", 1).show();
Handler h = new Handler() { @Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if (msg != null) {
String strMsg = (String) msg.obj;
System.out.println(strMsg);
} } };
//获取到Handler对象的消息
Message msg = h.obtainMessage();
msg.obj = "add";
msg.sendToTarget(); Looper.loop();// 进入loop中的循环,查看消息队列 }; }.start(); }
}

不知你是否理解,这个小Demo中,我们需要注意:

1  子线程也是可以有Handler的,其实Handler只是从当前的线程中获取到Looper来监听和操作MessageQueue的。

2 子线程需要先prepare()才能获取到Looper的,是因为在子线程只是一个普通的线程,其ThreadLoacl中没有设置过Looper,所以会抛出异常,而在Looper的prepare()方法中sThreadLocal.set(new Looper())是设置了Looper的。

而对于主线程里面的Handler,是没有以上的麻烦的,因为这个在Activity创建时,就已经初始化了Looper等其他工作了。

另外可以看下参考文章中的子线程中Toast

参考文章:

Android之Handler用法总结

Android Handler机制

子线程中Toast

[Android]Handler的消息机制的更多相关文章

  1. android handler传递消息机制

    当工作线程给主线程发送消息时,因为主线程是有looper的,所以不需要初始化looper,注意给谁发消息就关联谁的handler,此时用的就是主线程的handler handler会把消息发送到Mes ...

  2. 浅析Android中的消息机制(转)

    原博客地址:http://blog.csdn.net/liuhe688/article/details/6407225 在分析Android消息机制之前,我们先来看一段代码: public class ...

  3. 浅析Android中的消息机制(转)

    在分析Android消息机制之前,我们先来看一段代码: public class MainActivity extends Activity implements View.OnClickListen ...

  4. 浅析Android中的消息机制-解决:Only the original thread that created a view hierarchy can touch its views.

    在分析Android消息机制之前,我们先来看一段代码: public class MainActivity extends Activity implements View.OnClickListen ...

  5. 浅析Android中的消息机制

    在分析Android消息机制之前,我们先来看一段代码: public class MainActivity extends Activity implements View.OnClickListen ...

  6. android Handler及消息处理机制的简单介绍

    学习android线程时,直接在UI线程中使用子线程来更新TextView显示的内容,会有如下错误:android.view.ViewRoot$CalledFromWrongThreadExcepti ...

  7. 重温Android中的消息机制

    引入: 提到Android中的消息机制,大家应该都不陌生,我们在开发中不可避免的要和它打交道.从我们开发的角度来看,Handler是Android消息机制的上层接口.我们在平时的开发中只需要和Hand ...

  8. 谈谈对Android中的消息机制的理解

    Android中的消息机制主要由Handler.MessageQueue.Looper三个类组成,他们的主要作用是 Handler负责发送.处理Message MessageQueue负责维护Mess ...

  9. Android中的消息机制

    在分析Android消息机制之前.我们先来看一段代码: public class MainActivity extends Activity implements View.OnClickListen ...

随机推荐

  1. Unity3d:播放物理目录下的MP3文件

    u3d里,是支持播放MP3文件的,但要放到资源里,不支持播放物理目录下的MP3文件.由于界面上无需显示,只是当作背景音乐来播放,所以想到调用c#的组件来解决此问题.主要代码都在附件中,根据需要加到自己 ...

  2. 《高性能MySQL》

    <高性能MySQL>(第3版)讲解MySQL如何工作,为什么如此工作? MySQL系统架构.设计应用技巧.SQL语句优化.服务器性能调优.系统配置管理和安全设置.监控分析,以及复制.扩展和 ...

  3. (VC)解决绘图时闪烁问题的一点经验[转]

    转自:http://www.cnblogs.com/lidabo/p/3429862.html 清除屏幕闪烁 (转自网上) <一> 由于作图过于复杂和频繁,所以时常出现闪烁的情况,一些防止 ...

  4. extjs 点击复选框在表格中增加相关信息行

    功能效果:点击复选框在表格中自动增加相关信息行,复选框取消则表格中内容自动删除 初始效果大概是这样~~~~~ // 定义初始 存放表格数据 var gridItems = []; //省份复选框 va ...

  5. Flume-NG + HDFS + HIVE 日志收集分析

    国内私募机构九鼎控股打造APP,来就送 20元现金领取地址:http://jdb.jiudingcapital.com/phone.html内部邀请码:C8E245J (不写邀请码,没有现金送)国内私 ...

  6. window.location.href的使用方法

    http://hljqfl.blog.163.com/blog/static/40931580201122210573364/ 在写ASP.Net程序的时候,我们常常遇到跳转页面的问题,我们常常使用R ...

  7. IOS 7 Study - UIActivityViewController(Presenting Sharing Options)

    You want to be able to allow your users to share content inside your apps with theirfriends, through ...

  8. STL源码学习----lower_bound和upper_bound算法[转]

    STL中的每个算法都非常精妙,接下来的几天我想集中学习一下STL中的算法. ForwardIter lower_bound(ForwardIter first, ForwardIter last,co ...

  9. Java IO之File

    FILE类是用来实现获取文件.文件夹的类库工具,File并不是像类名所表示的那样仅仅是用来表示文件.它还能够用来表示文件夹. 所以能够用File来获取一个文件夹下的全部文件,甚至是文件夹中的文件. 一 ...

  10. Linux makefile 教程 很具体,且易懂

    近期在学习Linux下的C编程,买了一本叫<Linux环境下的C编程指南>读到makefile就越看越迷糊,可能是我的理解能不行. 于是google到了下面这篇文章.通俗易懂.然后把它贴出 ...