0

以下代码有一个线程负责使用特定套接字连接到服务器。连接的想法很好(在一个单独的线程中)。建立连接后,我尝试使用 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 没有被修改!

4

2 回答 2

0

尝试使用handler.sendMessage( handler.obtainMessage(...) )而不是handler.obtainMessage(...).sendToTarget().

由于obtainMessage()从全局消息池中检索到一个Message,可能是目标设置不正确。

于 2013-07-20T04:20:19.677 回答
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;
        }
    }
};
于 2013-07-20T05:09:20.930 回答