例子:
[color=red]PS:该例子使用HandlerThread可以使得onCreate方法和handlerMessage方法处于不同的线程中(推荐使用!!)
[/color]
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);
}
@Override
public void handleMessage(Message msg) {
System.out.println(Thread.currentThread().getId());
System.out.println("handlerMessage");
}
}
}
[color=red]PS:该例子使用HandlerThread可以使得onCreate方法和handlerMessage方法处于不同的线程中(推荐使用!!)
[/color]