gpt4 book ai didi

android - 从 Activity 中设置线程类中的文本

转载 作者:行者123 更新时间:2023-11-29 02:42:10 25 4
gpt4 key购买 nike

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

Activity :

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 类中的 Activity 的 TextView 中设置文本。我该怎么做?我认为 InflateLayout 没有帮助。

最佳答案

我会通过创建一个回调来解决这个问题,当从服务器接收到字符串时调用该回调。

interface ReceiveMessageListener {
void onMessageReceived (String message);
}

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

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

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

来自您的 Activity :

ReceiveMessages receive = new ReceiveMessages(input, this);

关于android - 从 Activity 中设置线程类中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43358351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com