Handlerマルチスレッド2(推奨)

1398 ワード

例:
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");
		}
    	
      }
}

PS:この例ではHandlerThreadを使用してonCreateメソッドとhandlerMessageメソッドを異なるスレッドにすることができます(推奨!)