2011-08-16 47 views
5

我有一個線程使用處理程序和消息發送數據到活動。一切工作正常時,活動暫停時除外:如何解決發送空消息給處理程序的死線程警告?

null sending message to a Handler on a dead thread 
java.lang.RuntimeException: null sending message to a Handler on a dead thread 
    at android.os.MessageQueue.enqueueMessage(MessageQueue.java:196) 
    at android.os.Looper.quit(Looper.java:173) 
    at pocket.net.ComD.stopConnection(ComD.java:154) 
    at pocket.net.ComD.finalize(ComD.java:184) 
    at dalvik.system.NativeStart.run(Native Method) 

在我的活動,我有下面的代碼,它可以讓我關閉所有的線程中打開網絡連接:

public void onPause() 
{ 
    if(this.myThread != null) { 
     this.myThread.stopConnection(); 
    } 
} 

在我的主題:

public void run() 
{ 
    this.setName("MessagesThread"); 
    if(this.initSocket()) 
    { 

      Looper.prepare(); 
      this.threadHandler = initHandler(); 
      Looper.loop(); 
    } 
    else 
    { 
     this.timeout(); 
    } 
} 

public void stopConnection() 
{ 
    if(this.threadHandler != null) { 
     this.threadHandler.removeMessages(ALIVE); // Remove a delayed message 
     this.threadHandler.getLooper().quit(); // Warning 
    } 
    this.connected = false; 
    if(this.client != null) { 
     this.client.close(); 
    } 
} 

private Handler initHandler() 
{ 
    return new Handler() { 

     public void handleMessage(Message msg) 
     { 
      switch(msg.what) 
      { 
       //Handling messages 
      } 
     } 
    } 
} 

當我收到警告「空發送消息到處理器上的死線」是該活動試圖將消息發送到線程或oppposite?

我該如何解決這個問題?

謝謝

+0

我以爲你想發送的數據工作線程到活動(UI線程)?如果是這樣,那麼工作者線程'sendMessage'就不應該在'Activity'中嗎?對不起,如果我誤解你的邏輯 –

+0

工作線程確實發送數據到活動。但是活動向工作線程詢問這些數據(和其他東西)。所以他們都有處理程序和消息 – grunk

回答

6

因爲Looper.quit()已經被調用,所以你得到的錯誤。

所以消息隊列是基本上不可用Looper.quit()被稱爲第一時間之後,因爲它排入具有空目標消息,這是不可思議的標識符的消息隊列停止入隊和出現「死」。

你需要做的是這樣的:

private boolean stoppedFlag= false; 
public void stopConnection() 
{ 
    if(this.threadHandler != null) { 
     this.threadHandler.removeMessages(ALIVE); // Remove a delayed message 
     if(!stoppedFlag){ 
      this.threadHandler.getLooper().quit(); // Warning 
      stopFlag = true; 
     } 
    } 
    this.connected = false; 
    if(this.client != null) { 
     this.client.close(); 
    } 
} 

要停止退出()被調用多次

Ref Looper

Ref Looper SOQ

相關問題