以下代码有一个线程负责使用特定套接字连接到服务器。连接的想法很好(在一个单独的线程中)。建立连接后,我尝试使用处理程序更新主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未被修改!
答案 0 :(得分:0)
尝试使用handler.sendMessage( handler.obtainMessage(...) )
代替handler.obtainMessage(...).sendToTarget()
。
由于obtainMessage()
从全局消息池中检索消息,因此可能未正确设置目标。
答案 1 :(得分:0)
尝试使用以下示例代码。我希望它会对你有所帮助。
byte[] buffer = new byte[32];
static int REFRESH_VIEW = 0;
public void onCreate(Bundle saveInstance)
{
RefreshHandler mRefreshHandler = new RefreshHandler();
final Message msg = new Message();
msg.what = REFRESH_VIEW; // case 0 is calling
final Bundle bData = new Bundle();
buffer = "connect".getBytes();
bData.putByteArray("bytekey", buffer);
msg.setData(bData);
mRefreshHandler.handleMessage(msg); // Handle the msg with key and value pair.
}
/**
* RefreshHandler is handler to refresh the view.
*/
static class RefreshHandler extends Handler
{
@Override
public void handleMessage(final Message msg)
{
switch(msg.what)
{
case REFRESH_VIEW:
final Bundle pos = msg.getData();
final byte[] buffer = pos.getByteArray("bytekey");
String strRecieved = new String(buffer);
//Update the UI Part.
status.setText("Set whatever you want. " + strRecieved);
break;
default:
break;
}
}
};