Note that there are some explanatory texts on larger screens.

plurals
  1. POPosting a Message to a running Thread using Handlers
    primarykey
    data
    text
    <p>I have code which calls a new Thread that connects to an IRC server. The thread has loop to listen for response from the IRC server and calls a method 'ProcessData' to action the response.</p> <p>On my UI I want to be able to 'QUIT' the IRC server in onStop and onPause. The trouble I have is that when I use a Handler to post a message to my IRC thread which sends a QUIT command to the IRC server it tells me that I am performing network operations on the UI thread.</p> <p>The handler is setup in my IRCManager class (this class extends Thread and is the class I run on a separate thread.</p> <pre><code>public Handler networkHandler = new Handler() { @Override public void handleMessage(Message msg) { try { processData((String) msg.obj); } catch (IOException e) { Log.e(TAG, "network handler given an object NOT of type String"); } super.handleMessage(msg); } }; </code></pre> <p>I use the handler from the main activity and instantiate it just after starting the network thread</p> <pre><code>irc.start(); networkHandler = irc.networkHandler; </code></pre> <p>In the onPause event I send a message to the handler</p> <pre><code>Message msg = new Message(); msg.obj = IRCManager.QUIT; networkHandler.sendMessage(msg); </code></pre> <p>EDIT: Here is the processData method</p> <pre><code>void processData(String data) throws IOException { if (data.contains("PING")) { String pingId = data.substring(6, data.length()); sendMessage(pong + pingId + "\n"); isConnected = true; Message msg = new Message(); msg.what = 1; msg.obj = "test"; handler.sendMessage(msg); } else if (data.contains("Welcome")) { sendMessage("PRIVMSG " + BOT_NAME + " JOIN " + siteId + "\n"); } else if (data.contains(IRCManager.QUIT)) { disconnect(); } else if (isClientConnected()) { Message msg = new Message(); msg.what = 2; msg.obj = "test"; handler.sendMessage(msg); } } </code></pre> <p>It seems that the handler isn't linking properly to the thread. Can anyone shed any light on how I can do this?</p> <p>My thread actually spends 99% of it's time in a while loop checking the inputstream from the IRC server. This may also have something to do with it.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload