从活动中设置线程类中的文本

时间:2017-04-12 00:33:21

标签: android

我有两个类,一个是Activity,一个是Thread类:

的活动:

public class MainActivity extends AppCompatActivity {

    ObjectInputStream inFromServer = null;
    ObjectOutputStream outToServer=null;
    Socket clientSocket = null;
    String userName;

    EditText message;
    static TextView textView;

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

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        message = (EditText)findViewById(R.id.txtMessage);
        textView = (TextView)findViewById(R.id.textView);

        try {
            clientSocket = new Socket("10.0.0.41", 10002);

            outToServer =
                    new ObjectOutputStream(clientSocket.getOutputStream());

            inFromServer =
                    new ObjectInputStream((clientSocket.getInputStream()));

        } catch (IOException e) {
            e.printStackTrace();
        }

        ReceiveMessages receiveMessages = new ReceiveMessages(inFromServer);
        receiveMessages.start();
    }

    public void onClickSend(View view) throws IOException {
        outToServer.writeObject("Eliran!" + message.getText().toString());
    }

    public void btnUserName(View view) throws IOException {
        EditText editText = (EditText)findViewById(R.id.userName);
        userName = editText.getText().toString();
        outToServer.writeObject(userName + "!");
    }
}

线程类:

public class ReceiveMessages extends Thread {

    ObjectInputStream inFromServer = null;

    public ReceiveMessages(ObjectInputStream inFromServer)
    {
        this.inFromServer = inFromServer;
    }

    public void run() {
        try {
            while (true) {
                String message = (String) inFromServer.readObject();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

我想在Thread类的活动的文本视图中设置文本。 我该怎么做? InflateLayout对我的思考没有帮助。

2 个答案:

答案 0 :(得分:0)

我会通过创建一个在从航空公司收到String时调用的Callback来实现它。

interface ReceiveMessageListener {
    void onMessageReceived (String message);
}

然后让我的Activity实现接口并在onMessageReceived回调中设置文本。

@Override
public void onMessageReceived (String message) {
    runOnUiThread(new Runnable() {
        @Override
        public void run () {
            textView.setText(message);
        }
    });
}

您还必须更改MessageReceive类的构造函数以获取MessageReceiveListener。

来自您的活动:

ReceiveMessages receive = new ReceiveMessages(input, this);

答案 1 :(得分:0)

只有UI线程可以与ui元素(例如textview)进行交互。尝试使用runOnOiThread或mainHandler.post()