Android_ [ Handler , Looper , Message,线程 ] 基础 原理

/**
@作者 : 西野奈留
@博客:http://blog.csdn.net/narunishino
@声明:本文仅在【CSDN 博客】发表。
*/

看了很多资料,始终弄不懂Android的多线程是怎么一回事,因为看的资料在主线程(UI线程)里面要么sendMessage(),要么handleMessage()。自己发自己收这么奇怪?

极力按压住无比烦躁的内心(花了超长时间在这上面都看不明白),继续找资料去看,最终耐心战胜了一切,终于让我找到了答案。

在Handler , Looper , Message当中,其实Looper才是主角(之前一直以为是Handler)。

1.一个线程只能有一个Looper,但可以有多个Handler。
2.Handler可以在任意线程发送消息,这些消息会被添加到关联的Looper的MessageQueue上。

//Handler构造函数里面的参数Looper是哪个线程的Looper,那sendMessage就会把消息发给哪个线程。
//下面的例子Looper.myLooper()指的是当前线程,所以sendMessage就会把消息发给当前线程的handleMessage。

Handler handler=new Handler(Looper.myLooper());
handler.sendMessage(message);

/*
ps:(来自于官方文档)Looper的getMainLooper()和myLooper()方法:

static Looper  getMainLooper()
Returns the application's main looper, which lives in the main thread of the application.

static Looper  myLooper()
Return the Looper object associated with the current thread.
*/

结论:不管在哪个线程都可以发消息或者接收消息,关键要看
Handler()构造函数里面的参数Looper,是哪个线程的Looper,就把消息发给哪个线程。参数为空的话,默认为当前线程。

参考:
http://www.jb51.net/article/33514.htm
http://www.bkjia.com/Androidjc/893149.html

-2015/10/8-
-End-

你可能感兴趣的:(多线程,android,handler,原理,looper)