使用 Handler 机制,首先需要创建一个Handler 对象,可以直接使用Handler 无参构造函创建Handler 对象,或者是继承Handler类,重写 handleMessage(Message msg)方法来创建handler对象。Google 官方提供了一个推荐的使用方式,代码如下∶
Class LooperThread extends Thread {
public Handler mHandler;
public void run()
{Looper.prepare();
mHandler = new Handler(){
public void handleMessage(Message msg){
// process incoming messages here
}
};
Looper.loop();
}
}
通过上一部分的分析,读者应该能够很容易理解上面这种方式。但是在实际的开发实践中,大部分的Handler 对象都是在主线程中创建的,此时已经存在了Looper 对象,并不需要调用Loopr.prepare()与 Looper.loop()方法,直接构建一个Handler 对象即可∶
private Handler mHandler = new Handler() {
public void handleMessage(Message msg)
{// process incoming messages here
}
};
这里我们使用Handler的sendMessage(Message msg)方法来发送消息,并使用handleMessage(Message msg)方法来接收消息,在布局代码中加入两个按钮,与两个TextView,当程序运行10秒修改TextView的内容,布局文件activity_main.xml代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/bind_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="绑定服务"
android:textSize="25dp"/>
<Button
android:id="@+id/unbind_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="解绑服务"
android:textSize="25dp"/>
<TextView
android:id="@+id/textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="无数据"
android:textSize=&#