以下代碼具有負責使用特定套接字連接到服務器的線程。連接的想法很好(在一個單獨的線程中)。連接建立後,我嘗試使用Handler更新主Activity,但它不會更新!使用處理程序更新活動
這裏是我的後臺線程代碼:
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) {
}
}
}
這裏是處理:
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;
}
};
我覈實,已建立連接(使用我的服務器代碼),但TextView的沒有修改!
在handleMessage中添加Log.d和一些調試消息 – pskink