How to fix null sending message to a Handler on a dead thread warning?
<p>I have a thread using handler and messages to send data to the activity. Everything work fine except when the activity is paused :</p>

<pre><code>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)
</code></pre>

<p>In my activity , i have the following code which lets me close all the network connection opened by the thread : </p>

<pre><code>public void onPause() 
{
    if(this.myThread != null) {
        this.myThread.stopConnection();
    }
}
</code></pre>

<p>In my Thread : </p>

<pre><code>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
            }
        }
    }
}
</code></pre>

<p>When i receive the warning "null sending message to a Handler on a dead thread" is that the activity trying to send a message to the thread or the oppposite ?</p>

<p>How can i fix this ?</p>

<p>Thanks</p>
