主线程和子线程的通讯之主线程用bundle发送数据到子线程
package com.wangcan;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println("当前线程的id是:"+Thread.currentThread().getId());
System.out.println("当前线程的名称是:"+Thread.currentThread().getName());
HandlerThread htThread=new HandlerThread("myht");
htThread.start();
Handler mHandler=new Handler(htThread.getLooper()){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//super.handleMessage(msg);
Bundle b2= msg.getData();
int age= b2.getInt("age");
String name = b2.getString("name");
Log.d("TAG", "age:" + age + ", name:" + name);
Log.d("TAG", "handler-->" + Thread.currentThread().getId());
Log.d("TAG", "handleMessage");
}
};
Message msg = mHandler.obtainMessage();
//将msg发送到目标对象,就是生成该msg的Handler对象
Bundle b = new Bundle();//使用Bundle来传递数据
b.putInt("age", 20);
b.putString("name", "John");
msg.setData(b);
msg.sendToTarget();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}