处理线程中的活动

时间:2013-11-02 19:17:02

标签: java android multithreading

我正在进行网络测验,我遇到了从线程处理活动的问题。这是Client的代码,它(成功)连接到服务器:

public class Client extends Thread {
    private MainActivity activity;
    private Socket socket;

    private DataInputStream dataIn;
    private DataOutputStream dataOut;
    private String host;
    private int port;

    public Client(String host, int port, MainActivity activity) {

            this.host = host;
            this.port = port;
            this.activity = activity;

//          At this point of the code, it works just great:
            activity.setQuestion("Question", "A", "B", "C", "D", 1);


            this.start();
    }

    private void processMessage( String msg ) {
        try {
            dataOut.writeUTF(msg);

        } catch (IOException e) {
            System.out.println(e);
        }
    }

    void handleMessage(String msg) {
        if (msg.equals("changeQuestion")) {

//          This does not work:
            activity.setQuestion("Question", "A", "B", "C", "D", 1);
        }
    }



    @Override
    public void run() {
        try {
            socket = new Socket( host, port );
            dataIn = new DataInputStream( socket.getInputStream() );
            dataOut = new DataOutputStream( socket.getOutputStream() );

            while (true) {
                String msg = dataIn.readUTF();
                handleMessage(msg);

            }
        } catch (IOException e) {
            System.out.println(e);
        }   


    }

}

setQuestion(...)中调用MainActivity方法,其中问题'和答案按钮的标题设置为字符串。 正如我的评论告诉你的那样,它在线程启动之前确实有效,但是一旦线程启动,它就会崩溃。

这是我的setQuestion(...)方法,位于MainActivity

public void setQuestion(String Q, String A, String B, String C, String D, int correctAnswer) {

    TextView tvQuestion = (TextView) findViewById(R.id.tvQuestion);
    tvQuestion.setText("");

    Button btnA = (Button) findViewById(R.id.btnAnswerA);
    Button btnB = (Button) findViewById(R.id.btnAnswerB);
    Button btnC = (Button) findViewById(R.id.btnAnswerC);
    Button btnD = (Button) findViewById(R.id.btnAnswerD);

    tvQuestion.setText(Q);
    btnA.setText(A);
    btnB.setText(B);
    btnC.setText(C);
    btnD.setText(D);

    this.correctAnswer = correctAnswer;
}

2 个答案:

答案 0 :(得分:0)

您的handleMessage()是从新的Thread调用的,而不是主UI线程。考虑将AsyncTask用于此类事情。这是干净的方式。

答案 1 :(得分:0)

无法从线程更新ui。从线程调用setQuestion,然后在setQuestion中将文本设置为按钮。

检查线程@

下的主题

http://developer.android.com/guide/components/processes-and-threads.html

您可以使用HandlerAsynctaskrunOnUiThread

activity.runOnUiThread(new Runnable() {
public void run() {
    activity.setQuestion("Question", "A", "B", "C", "D", 1);
 }
}