public class HandlethreadtestActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); HandlerThread myhandlethread=new HandlerThread("my_handler1");// 1.建立一個handlerthread 線程對象 my_handler 是這個線程對象的名稱 myhandlethread.start();//2. 啟動線程 MyHandle myhandle=new MyHandle(myhandlethread.getLooper());//4.綁定到建立的線程上 Message msg=myhandle.obtainMessage();//5. 擷取到msg對象 Bundle b=new Bundle(); b.putInt("age", 12); b.putString("name", "super_cj"); msg.setData(b);//在msg對象上綁定資料 msg.sendToTarget(); //把msg發送到綁定的線程上 } class MyHandle extends Handler //3. 建立一個handler的內部類 { public MyHandle() { } public MyHandle(Looper looper)//重載myhandle 讓父類Handler 把myhandlerthread 加入到線程隊列 { super(looper); }@Overridepublic void handleMessage(Message msg) {//線上程裡要做的事 就是你想非同步處理的代碼// TODO Auto-generated method stubsuper.handleMessage(msg);Bundle bb=msg.getData();//獲得msg 傳過來的資料int age=bb.getInt("age");String name=bb.getString("name");Toast.makeText(HandlethreadtestActivity.this, String.valueOf(age), Toast.LENGTH_LONG).show();try{Thread.sleep(5000);//暫停線程5秒Toast.makeText(HandlethreadtestActivity.this, name, Toast.LENGTH_LONG).show();}catch(Exception e){}} }}
我也是初學 自己寫下來忘記的時候來看看 呵呵 有錯誤的地方請幫忙指出 謝謝!