IntentService中使用Toask報錯sending message to a Handler on a dead thread

在本身IntentSevice繼承類中的onHandleIntent方法中寫Toast.makeText(getApplicationContext(), "sd不存在", Toast.LENGTH_SHORT).show();時不會有任何提示,logcat中提示「sending message to a Handler on a dead thread」錯誤。後從網上差報錯緣由瞭解到當一個線程的消息循環已經退出後,不能再給其發送消息不如就會報錯。後有從一個網站找到了解決方案,和產生錯誤的緣由。html

The problem here is that you are creating a Toast inside a thread that is managed by the IntentService. The system will use the Handler associated with this thread to show and hide the Toast.app


First the Toast will be shown correctly, but when the system tries to hide it, after the onHandleIntent method has finished, the error "sending message to a Handler on a dead thread" will be thrown because the thread on which the Toast was created is no longer valid, and the Toast will not disappear.ide


這裏的問題是,你正在建立一個由IntentService管理的Toast內部線程。該系統將使用與此線程關聯的處理程序,以顯示和隱藏Toast。首先,Toast將正確顯示出來,可是當系統試圖將其隱藏時onHandleIntent方法已經完成,「sending message to a Handler on a dead thread」的錯誤將被拋出,由於Toast在其上建立的線程再也不有效,且Toast不會消失。oop

解決方法:post

// create a handler to post messages to the main thread
    Handler mHandler = new Handler(getMainLooper());
    mHandler.post(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_SHORT).show();
        }
    });



引用:http://www.xuebuyuan.com/36739.html 網站

相關文章
相關標籤/搜索