您的位置:首页 > 编程语言

15-多线程编程(04-Handler和Message二)

2013-07-16 17:31 295 查看
package net.csdn.leigo.handler.message;

import net.csdn.leigo.handler.R;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {
private TextView mMsgTextView;

private Handler handler = new Handler() {

@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 3) {
int arg1 = msg.arg1;
int arg2 = msg.arg2;
int what = msg.what;
Object obj = msg.obj;
Bundle bundle = msg.getData();
String data = bundle.getString("data");
mMsgTextView.setText("arg1:" + arg1 + ", arg2:" + arg2
+ ", what:" + what + ", obj:" + obj.toString()
+ ", data:" + data);
}
}

};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mMsgTextView = (TextView) findViewById(R.id.tv_msg);
}

public void sendMessage(View v) {
new Thread(new Runnable() {

@Override
public void run() {
// ----------------------------------第一种方式-----------
// Message msg = Message.obtain();
// msg.arg1 = 100;
// msg.arg2 = 200;
// msg.what = 1;
// msg.obj = " hello ";
// handler.sendMessage(msg);
// -----------------------------------------------------
// ----------------------------------第二种方式-----------
// Message msg = Message.obtain(handler);
// msg.arg1 = 100;
// msg.arg2 = 200;
// msg.what = 2;
// msg.obj = " world ";
// msg.sendToTarget();
// -----------------------------------------------------
// ----------------------------------第三种方式-----------
//Message有很多重载方法,具体查看API,这里通过Bundle传递一个参数
Message msg = Message.obtain(handler, 3);
Bundle bundle = new Bundle();
bundle.putString("data", "hello world");
msg.obj = " android ";
msg.setData(bundle);
msg.sendToTarget();

}
}).start();

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  多线程 Handler Message