2011-08-25 22 views
7

我在工作線程中獲取Runtime Exception:Can't create handler inside thread that has not called Looper.prepare() while displaying the Toast message顯示Toast消息時出錯:無法在未調用Looper.prepare()的線程中創建處理程序

我有一個服務(運行在遠程進程),它創建一個對象。該對象負責連接到線程中的服務器。我得到了服務器的迴應。我想在吐司服務器上顯示消息。那時我得到這個例外。我嘗試使用handler.post在Handler中發佈它。但我仍然得到例外。

應該怎樣避免這種情況。

+0

[看這個](http://www.google.com/search?client=ubuntu&channel=fs&q=that+has+not+called+Looper.prepare%28%29&ie=utf-8&oe= UTF-8) –

+0

把你的服務代碼 –

回答

15

定義處理程序是這樣的:

private final Handler handler = new Handler() { 
     public void handleMessage(Message msg) { 
       if(msg.arg1 == 1) 
        Toast.makeText(getApplicationContext(),"Your message", Toast.LENGTH_LONG).show(); 
     } 
    } 

然後把下面的代碼,你需要證明你的麪包消息。

Message msg = handler.obtainMessage(); 
msg.arg1 = 1; 
handler.sendMessage(msg); 
+1

謝謝jainal這個解決方案工作:-)我早些時候嘗試過這個解決方案,但我在線程中創建處理程序。現在我改變了它的工作方式:-) –

+0

檢查這個庫'compile'c​​om.shamanland:xdroid-toaster:0.0.5'',它不需要'runOnUiThread()'或'Context'變量,所有例程都是走了!只需調用'Toaster.toast(R.string.my_msg);'這裏是例子:https://github.com/shamanland/xdroid-toaster-example –

相關問題