您好,登錄后才能下訂單哦!
Android HandlerThread使用方法詳解
HandlerThread 繼承自Thread,內部封裝了Looper。
首先Handler和HandlerThread的主要區別是:Handler與Activity在同一個線程中,HandlerThread與Activity不在同一個線程,而是別外新的線程中(Handler中不能做耗時的操作)。
用法:
import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Handler.Callback; import android.os.HandlerThread; import android.os.Message; public class MainActivity extends Activity { HandlerThread handlerThread = new HandlerThread("test"); Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); System.out.println("cur_id="+Thread.currentThread().getId()); handlerThread.start(); System.out.println("handlerThread.id=" + handlerThread.getId()); //post(runnable),只是直接運行了run(),run()內ThreadId與UIThread是一樣的 // handler = new Handler(); //post(runnable),將runnable運行在handlerThread中,這是非UIThread的 handler = new Handler(handlerThread.getLooper(), new Callback() { @Override public boolean handleMessage(Message msg) { System.out.println("receive message.whatA=" + msg.what); if (msg.what == 1) { return true;//不再向外層傳遞 } else { return false; //外層的handleMessage() 繼續執行 } } }) { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); System.out.println("receive message.whatB=" + msg.what); } }; handler.post(new Runnable() { @Override public void run() { System.out.println("handler_post_cur_id="+Thread.currentThread().getId()); handler.sendEmptyMessage(1); handler.sendEmptyMessage(2); } }); } }
運行結果:
01-23 07:12:31.590: I/System.out(12386): cur_id=1 01-23 07:12:31.590: I/System.out(12386): handlerThread.id=1866 01-23 07:12:31.590: I/System.out(12386): handler_post_cur_id=1866 01-23 07:12:31.600: I/System.out(12386): receive message.whatA=1 01-23 07:12:31.600: I/System.out(12386): receive message.whatA=2 01-23 07:12:31.600: I/System.out(12386): receive message.whatB=2
如有疑問請留言或到本站社區交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。