The following code has a thread that is responsible of connection to a server using a a specific socket. The idea of connecting works fine (in a separate thread). After the connection is established, I tried to update the main Activity using a Handler but it wouldn't updated!
Here is my code for the background thread:
public class SocketThread extends Thread {
private final Socket socket;
private final InputStream inputStream;
private final OutputStream outputStream;
byte[] buffer = new byte[32];
int bytes;
public SocketThread(Socket sock) {
socket = sock;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
}
catch (IOException e) {}
inputStream = tmpIn;
outputStream = tmpOut;
EntryActivity.connected = true;
buffer = "connect".getBytes();
EntryActivity.UIupdater.obtainMessage(0, buffer.length, -1, buffer).sendToTarget();
}
public void run() {
try {
while (!Thread.currentThread().isInterrupted()) {
bytes = inputStream.read(buffer);
EntryActivity.UIupdater.obtainMessage(0, bytes, -1, buffer).sendToTarget();
}
} catch (IOException e) {
}
}
}
And here is the handler:
static Handler UIupdater = new Handler() {
public void handleMessage(Message msg) {
int numOfBytes = msg.arg1;
byte[] buffer = (byte[]) msg.obj;
strRecieved = new String(buffer);
strRecieved = strRecieved.substring(0, numOfBytes);
if (strRecieved.equals("connect"))
// Update a TextView
status.setText(R.string.connected);
else
// Do something else;
}
};
I verified that the connection was established (using my Server code), but the TextView was not modified!