主要代碼段:
package com.demo.thorn.handlerdemo;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
/*
* 1. 因爲 android 的 UI 線程默認調用了 Looper 的 prepare() 方法,所以在主線程中調用時不需要調用這個方法
* 2. 一個線程中,Handler 的 prepare() 方法只會執行一次 , 因此,Looper 對象和 MessageQueue 對象在這個線程中最多也只有一個
* 3. Handler 的原理可描述爲 多個 handler 將多個 messages 不定期傳遞給 Looper 對象創建的 MessageQueue 對象(若 MessageQueue 對象沒有接收到消息,則阻塞),MessageQueue 對象將這些 messages 排序後再通過回調的方法返還給這些 handler 對象
* 4. 不僅僅主線程可以調用 Handler ,子線程也可以調用,並且這種代碼處理思路可以應用到很多地方
* */
public class MainActivity extends AppCompatActivity {
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = findViewById(R.id.mText);
}
public void fun1(View view) {
final Handler handler1 = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(msg.what==123){
mTextView.setText("方法一設置 UI 成功了");
}else{
mTextView.setText("方法一設置 UI 成功了222");
}
}
};
new Thread(new Runnable() {
@Override
public void run() {
// 做一些耗時操作,這裏是子線程,完成後發送 message,這裏延時一秒
Looper.prepare();//因爲不在主線程中,所以Looper的prepare() 方法不會自動執行
boolean i = handler1.sendEmptyMessageDelayed(123,1000);
}
}).start();
}
public void fun2(View view) {
Handler handler2 = new Handler();
handler2.post(new Runnable() {
@Override
public void run() {
mTextView.setText("方法二設置 UI 成功了");
}
});
}
}
佈局文件代碼:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.demo.thorn.handlerdemo.MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="fun1"
android:text="1. 創建內部類的方法" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="fun2"
android:text="2. 使用handler的post方法" />
<TextView
android:id="@+id/mText"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_marginTop="30dp"
android:background="@color/colorAccent"
android:gravity="center"
android:text="hello world"
android:textColor="@color/colorPrimary" />
</LinearLayout>