Android异步线程与Bundle消息传递
package com.lzr; /////验证异步线程 /////先修改AndroidManifest.xml来默认启动HanderTest2这个Activity ////使用Looper来启动另一个线程实现handler ////HandlerThread对象用法 ////Bundle对象用法 import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; public class Handlertest2 extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.main); //打印当前线程的ID System.out.println("Activity--->"+Thread.currentThread().getId()); ///生成一个HandlerThread线程对象,实现使用Looper来处理消息队列的功能,这个类由Android提供 HandlerThread handlerThread=new HandlerThread("handler_thread"); ////在使用HandlerThread的getLooper()方法前,必须先调用start()启动线程 handlerThread.start(); //// MyHandler myHandler=new MyHandler(handlerThread.getLooper()); Message msg=myHandler.obtainMessage(); ////生成Bundle对象 Bundle b=new Bundle(); b.putInt("age", 25); b.putString("name", "make"); msg.setData(b); ////将msg发送到目标对象,所谓目标对象,就是生成该对象的handler对象,如myHandler msg.sendToTarget();///调用当生成的对象发送给handleMessage(Message msg) } class MyHandler extends Handler{ public MyHandler() {} ////使用looper来使Handler从另外一个线程中的消息队列中取得数据 public MyHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub ///super.handleMessage(msg); Bundle b=msg.getData(); int age=b.getInt("age"); String name=b.getString("name"); System.out.println("age is"+age+" name is"+name); System.out.println("handler--->"+Thread.currentThread().getId()); System.out.println("handlerMessage"); } } }
相关推荐
huha 2020-10-16
xfcyhades 2020-11-20
sgafdsg 2020-11-04
Michael 2020-11-03
fengyeezju 2020-10-14
ziyexiaoxiao 2020-10-14
业余架构师 2020-10-09
OuNuo0 2020-09-29
moses 2020-09-22
Angelia 2020-09-11
qinxu 2020-09-10
刘炳昭 2020-09-10
Nostalgiachild 2020-09-07
Nostalgiachild 2020-08-17
leavesC 2020-08-14
一青年 2020-08-13
AndroidAiStudy 2020-08-07
ydc0 2020-07-30
绿豆饼 2020-07-28