例子如下:在xml中有一个TextView.
package com.example.handler;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView text;
Handler myHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text);
//新建handler对象,用于发送和接受,并处理消息
myHandler = new Handler(){
//接受并处理
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Bundle mData = msg.getData();
String str = mData.getString("key");
text.setText(str);
}
};
//
new Thread(){
@Override
public void run() {
super.run();
Message msg = new Message();
Bundle data = new Bundle(); //通过bundle 携带数据
data.putString("key", "我的名字:水手");
msg.setData(data);
myHandler.sendMessage(msg);//handler发送消息
}
}.start();
//
}
}
结果: