Android : Android: Communicate with worker thread to send messages

on Friday, September 19, 2014


I am trying to send messages from one android device to another via tcp. The sending device sends to a PC used as server which then sends the message to the other device. In order to receive messages I run a thread parallel to the UI-thread which updates the user interface using a handler to show the message. This works fine.


Right now I am using an AsyncTask to send messages, which creates a socket, then sends the message an then closes the socket again. So every time I want to send a message I have to connect and disconnect.



public class SendTask extends AsyncTask<String, Void, Void> {

static final String TAG = "SendTask";

private Socket soc;
private String theIp;
private int thePort;

public SendTask(String pIp, int pPort){
theIp = pIp;
thePort = pPort;
}

@Override
protected Void doInBackground(String... arg0) {

try {
soc = new Socket(theIp, thePort);
soc.getOutputStream().write(arg0[0].getBytes());
soc.close();
} catch (Exception e) {
Log.d(TAG, "failed to create socket");
e.printStackTrace();
}

return null;
}

}


I would rather have a solution where I create a thread which opens the socket and then every time a button is clicked sends a text recevied from an EditText. Is there a solution for this that is similar to the receiving thread? I am struggling with how to tell the created thread when to send a message without accessing the UI from that Thread.


The sending Thread looks as follows:



public class ReceiveClient implements Runnable {

static final String TAG = "ReceiveClient";

public static final int NEW_INPUT = 101;

private Socket soc;
private String theIp;
private int thePort;
Handler handler;

public ReceiveClient(String pIp, int pPort, Handler pHandler){
this.theIp = pIp;
this.thePort = pPort;
handler = pHandler;
}

@Override
public void run() {
Log.d(TAG, "try to create socket");
try {
soc = new Socket(theIp, thePort);
} catch (Exception e) {
Log.d(TAG, "failed to create socket");
e.printStackTrace();
}
Log.d(TAG, "running");
try {
while (!Thread.currentThread().isInterrupted()) {
byte b[] = new byte[16];
int count = soc.getInputStream().read(b, 0, 16);
if(count > 0){
String s = new String(b);
Log.d(TAG, "received: " + s);
displayMessage(s);
}
}
Log.d(TAG, "done");
}catch (Exception e) {
System.err.println(e);
}
}

private void displayMessage(String text){
Message msg = handler.obtainMessage();
msg.what = NEW_INPUT;
msg.obj = text;
handler.sendMessage(msg);
}
}

0 comments:

Post a Comment