HandlerThread分線程啟動handler

來源:互聯網
上載者:User
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 MainActivity extends Activity{/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);// 列印UI線程的名稱System.out.println("onCreate  CurrentThread = "+ Thread.currentThread().getName());setContentView(R.layout.activity_main);// 實現了使用Looper來處理訊息佇列的功能HandlerThread handler = new HandlerThread("handler_Thread");handler.start();MyHandler myHandler = new MyHandler(handler.getLooper());Message msg = myHandler.obtainMessage();msg.obj = "abc";Bundle data = new Bundle();data.putString("title", "你好嗎");data.putString("info", "哈哈哈哈");msg.setData(data);// 將msg發送到對象,所謂的目標對象就是產生該msg對象的Handler對象msg.sendToTarget();}class MyHandler extends Handler {public MyHandler() {}public MyHandler(Looper looper) {super(looper);}@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stubString s = (String) msg.obj;Bundle data = msg.getData();String title=data.getString("title");String info=data.getString("info");               System.out.println("title is " + title + ", info is" + info);              System.out.println("msg.obj is " + s);  System.out.println(Thread.currentThread().getId());System.out.println("handlerMessage");}}}

  HandlerThread繼承與Thread,所以本身就是一個線程。他類似於建立了一個含有Looper對象的線程類,而Looper可以用於建立Handler類,這樣我們就不用自己執行個體化Looper對象,調用preare和Loop了,而是直接調用HandlerThread。與普通的Thread相比,就是多了Looper對象。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.