主要用于跨线程 Thread、Healder、Looper、Timer 结合使用
Activity <-> Looper -> MessageQueue
Handler <-> Looper -> MessageQueue
Looper == Message Queue Manager
Looper.getMainLooper(); //获取主线程Looper
Looper.myLooper();//获取当前线程Looper???
Looper.prepare();//创建消息队列,子线程默认没有消息队列,主线程队列无需调用
Looper.prepareMainLooper();//创建主线程消息队列
Looper.loop();//启动队列循环
本地消息
public void btn_click1(View view){
new Thread(new Runnable() {
@Override
public void run() {
List<String> list1=new ArrayList<String>();
list1.add("a");
list1.add("b");
list1.add("c");
//自定义信息
Message msg = myHandler.obtainMessage();
//信息配置
Bundle bundle = new Bundle();
bundle.putBoolean("msg1",true);
bundle.putInt("msg2",10);
bundle.putString("msg3","a");
bundle.putSerializable("msg4", (Serializable)list1);
msg.setData(bundle);
//信息发送方法1
msg.setTarget(myHandler);
msg.sendToTarget();
//信息发送方法2
//myHandler.sendMessage(msg);
}
}).start();
}
private final Handler myHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
Bundle bundle = msg.getData();
Boolean bool = bundle.getBoolean("msg1");
int valueInt = bundle.getInt("msg2");
String valueStr=bundle.getString("msg3");
Object obj=bundle.get("msg4");
List<String> list1=(List<String>)obj;
if(list1!=null){
for(String item : list1){
Log.i("acu","msg4=" + item);
}
}
AlertDialog.Builder builder = new AlertDialog.Builder(Test1.this);
builder.setIcon(android.R.drawable.ic_menu_help);
builder.setTitle("提示");
builder.setMessage("跨线程调用演示");
builder.setIcon(R.drawable.ic_launcher);
builder.setPositiveButton("ok",null);
builder.setNegativeButton("cancel",null);
AlertDialog ad=builder.create();
ad.show();
Toast.makeText(Test1.this, "跨线程调用演示", 3000).show();
super.handleMessage(msg);
}
};