首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > 移动开发 >

Handler多线程2(推荐)

2012-08-29 
Handler多线程二(推荐)例子:public class HandlerTest extends Activity {/** Called when the activity i

Handler多线程二(推荐)
例子:

public class HandlerTest extends Activity {    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        System.out.println("activity-->"+Thread.currentThread().getId());        HandlerThread h = new HandlerThread("handler_thread");        h.start();        MyHandler myHandler = new MyHandler(h.getLooper());        Message m = myHandler.obtainMessage();//参数传递        m.arg1 = 123;        m.obj = "abc";//通过Bundle传递参数        Bundle b = new Bundle();        b.putInt("age", 20);        b.putString("name", "guanrl");        m.setData(b);        //将Msg发送到目标对象,所谓的目标对象,就是生成该msg对象的handler对象        m.sendToTarget();    }    class MyHandler extends Handler{      public MyHandler(Looper looper){        super(looper);     }@Overridepublic void handleMessage(Message msg) {System.out.println(Thread.currentThread().getId());System.out.println("handlerMessage");}          }}

PS:该例子使用HandlerThread可以使得onCreate方法和handlerMessage方法处于不同的线程中(推荐使用!!)

热点排行