Handler是用来实现线程之间的通信的。
首先在主线程当中实现Handler的handleMessage()方法,然后在Worker Thread当中通过Handler发送消息。
下面以例子说明,在主界面当中创建一个TextView 和一个Button,用户点击按钮,两秒后TextView发生变化。该例子用于模拟从服务器中获取数据,再反馈给UI界面。
activity_main.xml
<RelativeLayout 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"
tools:context="${packageName}.${activityClass}" >
<TextView
android:id="@+id/textViewId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="数据" />
<Button
android:id="@+id/buttonId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/textViewId"
android:text="发送消息"/>
</RelativeLayout>
MainActivity.java
package com.wyb.s02_e07_handler02;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView textView;
private Button button;
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.textViewId);
button = (Button)findViewById(R.id.buttonId);
handler = new MyHandler();
button.setOnClickListener(new ButtonListener());
}
class MyHandler extends Handler{
@Override
public void handleMessage(Message msg) {
System.out.println("Thread-------->"+Thread.currentThread().getName());
String s = (String)msg.obj;
textView.setText(s);
}
}
class ButtonListener implements OnClickListener{
@Override
public void onClick(View v) {
Thread t = new NetworkThread();
t.start();
}
}
class NetworkThread extends Thread{
@Override
public void run() {
System.out.println("Thread-------->"+Thread.currentThread().getName());
//模拟访问网络,当运行线程时,先休眠2秒
try {
Thread.sleep(2*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//变量s的值模拟从网络中获取的数据
String s = "从网络中获取的数据";
//textView.setText(s);这样的做法是错误的,因为在Andorid系统当中,只有在Main Thread当中才能操作UI
Message msg = handler.obtainMessage();
msg.obj = s;
handler.sendMessage(msg);
}
}
}
可以看到Handler对象是在主线程当中生成的,但在NetworkThread当中利用handler发送了一个msg给消息队列。然后再在handleMessage把该消息对象取出来。从而实现了Worker Thread 与 Main Thread 之间的通信。