收到Websocket消息时,在Textview中显示消息

时间:2015-02-27 04:18:41

标签: android textview java-websocket

这是我在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);
}

当服务器发送消息时,它不会显示在textview中。但是在Logcat中会显示回复。可能是什么问题?

2 个答案:

答案 0 :(得分:0)

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

有些事情......

Handler mHandler = new Handler(); 
// ...
// onMessage:
mHandler.post(new Runnable() {
    public void run() {
        //.. update UI
    }
};

答案 1 :(得分:0)

如果您要在另一个帖子中更新TextView,那么您应该在

下面做一些事情
textView.post(new Runnable() {
    public void run() {
        textView.setText(yourText);
    } 
}