您的位置:首页 > 移动开发 > Android开发

Android Handler 机制以及各方法所在线程原理分析

2017-12-21 20:32 519 查看
Handler 的定义及作用:

因为有的文章已经说得比较清楚了,就直接引用下。这里借鉴http://mobile.51cto.com/aprogram-442833.htm

一、Handler的定义:

主要接受子线程发送的数据, 并用此数据配合主线程更新UI。

解释:当应用程序启动时,Android首先会开启一个主线程 (也就是UI线程) , 主线程为管理界面中的UI控件, 进行事件分发, 比如说, 你要是点击一个 Button ,Android会分发事件到Button上,来响应你的操作。  如果此时需要一个耗时的操作,例如: 联网读取数据,    或者读取本地较大的一个文件的时候,你不能把这些操作放在主线程中,如果你放在主线程中的话,界面会出现假死现象, 如果5秒钟还没有完成的话,会收到Android系统的一个错误提示  "强制关闭"。  这个时候我们需要把这些耗时的操作,放在一个子线程中,因为子线程涉及到UI更新,,Android主线程是线程不安全的,
也就是说,更新UI只能在主线程中更新,子线程中操作是危险的。 这个时候,Handler就出现了。,来解决这个复杂的问题 ,由于Handler运行在主线程中(UI线程中),  它与子线程可以通过Message对象来传递数据, 这个时候,Handler就承担着接受子线程传过来的(子线程用sedMessage()方法传弟)Message对象,(里面包含数据)  , 把这些消息放入主线程队列中,配合主线程进行更新UI。

二、Handler一些特点

handler可以分发Message对象和Runnable对象到主线程中, 每个Handler实例,都会绑定到创建他的线程中(一般是位于主线程),它有两个作用:

(1)安排消息或Runnable 在某个主线程中某个地方执行;

(2)安排一个动作在不同的线程中执行。

Handler中分发消息的一些方法

post(Runnable)

postAtTime(Runnable,long)

postDelayed(Runnable long)

sendEmptyMessage(int)

sendMessage(Message)

sendMessageAtTime(Message,long)

sendMessageDelayed(Message,long)

以上post类方法允许你排列一个Runnable对象到主线程队列中,

sendMessage类方法, 允许你安排一个带数据的Message对象到队列中,等待更新。

(AtTime 和Delayed只是把handler传递时间进行确定,或者延迟一定时间。)

==========================================================

原创分割线

至于Message队列的相关知识,这里就不赘述了。接下来主要分析这些方法的线程关系。

可以看到参数方法主要分为两种,Message和Runnable

1.Message 类

简单来说Message类主要是在线程经过一系列计算后,需要更新一部分信息到UI上。

根据之前的说法,更新UI需要到主线程。而线程计算的结果就是使用Message来从子线程传递到主线程的。

用法:

如下面例子的msg.what是这条Message的唯一标志,在Handler的HandleMessage方法中识别出来后可以读取出其中set的Bundle 对象,然后进行UI更新

public class MainActivity extends AppCompatActivity {

private final int MESSAGE_ONE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case MESSAGE_ONE:
Bundle bundle = msg.getData();
Toast.makeText(getApplicationContext(),bundle.getString("ToastMessage"),Toast.LENGTH_LONG).show();
}

Log.d("zhang556","thread4444: "+ Thread.currentThread().getId());
}
};
Log.d("zhang556","thread11111: "+ Thread.currentThread().getId());

new Thread(){
@Override
public void run() {
super.run();
Log.d("zhang556","thread3333: "+ Thread.currentThread().getId());
Message msg = new Message();
Bundle bundle = new Bundle();
bundle.putString("ToastMessage","I am Handler");
msg.what = MESSAGE_ONE;
msg.setData(bundle);
mHandler.sendMessage(msg);
}
}.start();

}
}
这里运行后Log如下

可以看到进行数据处理的线程和更新的线程并不是同一个,并且真机运行可以正常出现上面的Toast

接下来到源码看下Message做了什么

我这里并没有追的非常深,利用调用查看了下 Looper中(Looper是取消息的一个类)

public static void loop() {
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final 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();

for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}

// This must be in a local variable, in case a UI event sets the logger
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}

final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}

if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}

// 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.recycleUnchecked();
}
}

可以看到这里有个死循环取消息,并且最后使用
msg.target.dispatchMessage(msg);


进行分发。

接下来是走到这里

public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}这里的msg.callback 其实是一个Runnable对象。开始我们讲了有两种使用方法,一种使用message做参数,一种使用Runnable

没错,如果你调用的是message方法使用handler这里msg.callback 就为空(我到代码里看了确实是会把Runnable赋给msg.callback
,这里就不贴代码了)。所以这次是会回调我们的handleMessage,因此还是主线程调用的。

2.Runnable类

其实解释了刚才的dispatchMessage(Message msg)

大家也都应该知道了,Runnable作为一个对象来保存一些操作,但是实际没有开启线程,直接调用了

    private static void handleCallback(Message message) {

        message.callback.run();

    }

依然是回调的方法来执行你传过来的Runnable对象。下面还是一个Demo验证下Handler的post方法:

public class MainActivity extends AppCompatActivity {

private final int MESSAGE_ONE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case MESSAGE_ONE:
Bundle bundle = msg.getData();
Toast.makeText(getApplicationContext(),bundle.getString("ToastMessage"),Toast.LENGTH_LONG).show();
}

Log.d("zhang556","thread4444: "+ Thread.currentThread().getId());
}
};
Log.d("zhang556","thread11111: "+ Thread.currentThread().getId());
mHandler.post(new Runnable() {
@Override
public void run() {
Log.d("zhang556","thread22222: "+ Thread.currentThread().getId());
}
});

// new Thread(){
// @Override
// public void run() {
// super.run();
// Log.d("zhang556","thread3333: "+ Thread.currentThread().getId());
// Message msg = new Message();
// Bundle bundle = new Bundle();
// bundle.putString("ToastMessage","I am Handler");
// msg.what = MESSAGE_ONE;
// msg.setData(bundle);
// mHandler.sendMessage(msg);
// }
// }.start();

}
}运行结果:

12-23 14:56:34.651 11460-11460/com.example.administrator.downloaddemo D/zhang556: thread11111: 1

12-23 14:56:34.722 11460-11460/com.example.administrator.downloaddemo D/zhang556: thread22222: 1

可以看到与主线程是同一线程,所以大家在进行异步操作的时候一定要使用handler传递message的这种方法。

而post一个runnable对象的方法,个人感觉是方便切换到主线程进行UI操作了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐