前言
上一篇blog(处女男学Android(四)---Handler进阶篇之Handler、Looper、MessageQueue工作机制)介绍了关于Handler、Looper、MessageQueue的工作原理和源码分析,已经对Handler的整体工作过程有了一个较为深刻的了解,那么关于Handler还有一些重要的知识点,本篇就具体记录一下关于Handler的post方法的用法和工作原理。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="10dp" > <TextView android:id="@+id/tv_textView1" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1.0" android:gravity="center_horizontal|center_vertical" android:text="Text Example" android:textSize="15sp" /> <Button android:id="@+id/btn_button1" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="Change Text" /> </LinearLayout>
package com.example.handlertest; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class ThirdActivity extends Activity { private Button button; private TextView textView; private Handler handler = new Handler(); //在主线程定义一个handler @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.third); textView = (TextView) findViewById(R.id.tv_textView1); button = (Button) findViewById(R.id.btn_button1); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { MyThread mThread = new MyThread(); mThread.start(); //启动MyThread } }); } class MyThread extends Thread { @Override public void run() { handler.post(new Runnable() { //通过post方法发送消息 @Override public void run() { String currentThreadName = Thread.currentThread().getName(); System.out.println("当前线程名称为--->" + currentThreadName); //打印线程名 try { Thread.sleep(1000 * 2); // 模拟一个2s的耗时任务 } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } String s = "\n has been changed !"; textView.setText(textView.getText() + s); textView.setTextColor(Color.RED); // 更改UI } }); } } }
public final boolean post(Runnable r) { return sendMessageDelayed(getPostMessage(r), 0); }
private static Message getPostMessage(Runnable r) { Message m = Message.obtain(); //新建了一个Message对象 m.callback = r; //将传进来的Runable对象赋给Message对象的callback属性,Message的callback属性本身就是Runnable对象 return m; //返回赋值之后的Message对象 }
public final boolean sendMessage(Message msg) { return sendMessageDelayed(msg, 0); }
public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); //当Message对象的callback属性不为空时则调用handleCallback(msg)方法 } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }
private static void handleCallback(Message message) { message.callback.run(); }