前幾天改一個小問題用到了線程,涉及到線程就要考慮線程的開啓和關閉。如果你想着不用的時候直接拿線程對象的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);