0

这是我在 android 中的 websocket 客户端。这是一个快速测试,服务器的回复应该显示在TextView.

Boolean status1 = false;
static String msg = "reply ";   


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    java.lang.System.setProperty("java.net.preferIPv6Addresses", "false");
    java.lang.System.setProperty("java.net.preferIPv4Stack", "true");

    final TextView text = (TextView) findViewById(R.id.textView1);
    final TextView text1 = (TextView) findViewById(R.id.textView2);
    final Button button = (Button) findViewById(R.id.button1);


    try {
        final WebSocketClient client = new WebSocketClient(new URI(
                "ws://10.0.2.2:8080/_024_WebSocketTest4/echo")) {

            @Override
            public void onOpen(ServerHandshake handshakedata) {
                Log.d("1", "open");
                status1 = true;

            }

            @Override
            public void onMessage(String message) {

                msg += message;
                Log.d("reply", message);

                print(text1);

            }

            @Override
            public void onError(Exception ex) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onClose(int code, String reason, boolean remote) {
                status1 = false;

            }
        };

        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                connect(client);


            }
        });




    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}


public void connect(WebSocketClient client) {

    final TextView text = (TextView) findViewById(R.id.textView1);
    client.connect();

    while (!status1) {

    }

    text.setText(client.getReadyState().toString());
    client.send("Hello");
    //final TextView text1 = (TextView) findViewById(R.id.textView2);

    //text1.setText(msg);
}

public void print(TextView text1) {

    Log.d("print", msg);
    text1.setText(msg);
}

当服务器发送消息时,它没有显示在文本视图中。但在 Logcat 中会显示回复。可能是什么问题呢?

4

2 回答 2

0

您可能需要从主线程更新 TextView。

类似的东西..

Handler mHandler = new Handler(); 
// ...
// onMessage:
mHandler.post(new Runnable() {
    public void run() {
        //.. update UI
    }
};
于 2015-02-27T04:40:39.407 回答
0

如果你要在另一个线程中更新你的 TextView 那么你应该在下面做一些事情

textView.post(new Runnable() {
    public void run() {
        textView.setText(yourText);
    } 
}
于 2015-02-27T05:00:45.727 回答