如何更改主线程外的视图?

时间:2012-07-21 18:11:37

标签: android multithreading tcp

我想在手机和PC之间建立客户端服务器连接,

package com.example.tcptest;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.support.v4.app.NavUtils;

public class MainActivity extends Activity {

    TCPClient tcpclient;
    Boolean isconnected = false;
    Button connectBtn;
    Button sendBtn;
    TextView ipport;
    TextView sendtext;
    TextView rcvtext;
    Timer timer;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Buttons
        connectBtn=(Button)findViewById(R.id.connectbtn);
        sendBtn=(Button)findViewById(R.id.sendbtn);

        ipport = (TextView)findViewById(R.id.serverip);
        sendtext = (TextView)findViewById(R.id.sendtxt);
        rcvtext = (TextView)findViewById(R.id.console);      

        connectBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {   
                //String[] i_po = ((String)ipport.getText()).split(":");
                //tcpclint = new TCPClient(i_po[0], Integer.parseInt(i_po[1]));         

                Thread cThread = new Thread(new ClientThread());
                cThread.start();                
            }

        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    public class ClientThread implements Runnable {     
        public void run() {
            tcpclient = new TCPClient("192.168.0.101", 5000);
            tcpclient.connect();
            tcpclient.send("hello server");
            rcvtext.setText(tcpclient.getdata());           
        }
    }

}

在这种情况下,我无法更改rcvtext的文本,因为它在线程中运行,如果连接成功,我是否有可能更改rcvtext的内容喜欢将日志写入rcvtext

1 个答案:

答案 0 :(得分:4)

ClientThread的{​​{1}}方法中,执行此操作:

run()

告诉Android在UI线程(主应用程序线程)上运行它,而不是当前线程。