Android線程開啓與關閉

前幾天改一個小問題用到了線程,涉及到線程就要考慮線程的開啓和關閉。如果你想着不用的時候直接拿線程對象的Destroy方法就太天真了,相信你自己這樣做都感到不敢相信。其實你的這種感覺是對的,Destroy方法的確是不能用的。

也去百度了一下,見到了兩種方法:

第一種:用HandlerThread;

HandlerThread thread = new HandlerThread("MyHandlerThread");
thread.start();
mHandler = new Handler(thread.getLooper());
mHandler.post(mBackgroundRunnable);//mBackgroundRunnable爲線程對象

第二種:直接用Handler;

Handler mHandler = new Handler();
mHandler.post(mBackgroundRunnable);//mBackgroundRunnable爲線程對象

在銷燬對象時使用mHandler.removeCallbacks(mBackgroundRunnable);

發佈了5 篇原創文章 · 獲贊 4 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章