gpt4 book ai didi

java - 如何在我的应用程序 android 中编写 StreamReader?

转载 作者:搜寻专家 更新时间:2023-11-01 09:09:42 25 4
gpt4 key购买 nike

我要开发一个从服务器接收消息的 Android 应用程序,但我可以连接到服务器但无法接收消息,因为当我单击 Button 连接 block 时。我认为这是因为循环,但不知道如何以另一种方式解决这种情况,非常感谢您的帮助。

简而言之,我想知道是否有另一种方法来检测我何时收到消息并显示它。

更新:我找到了这样的解决方案:

String IP;

String comando;

PrintWriter msgout;

BufferedReader msgin;

Socket socket;

private ConnectedThread mConnectedThread;



public void connect(){ //Function to Button connect

IP = edit.getText().toString();

try {

InetAddress serverAddr = InetAddress.getByName(IP); //TCPServer.SERVERIP

Socket socket = new Socket(serverAddr, 4444); //Porta 4444 serverAddr
PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
msgout = out;

BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
msgin = in;

zav.text1.setText("Connectado.");

//Wait to mensages
mConnectedThread = new ConnectedThread();
mConnectedThread.start();

} catch (Exception e) {
text1.setText("Erro! Não conectado." + e);
}
}

public void send(String message){

try {

msg.println(message);


} catch(Exception e) {
text1.setText("Erro! Comando não enviado." + e);
}
}

private class ConnectedThread extends Thread {

public void run(){

while(true){

//Read
try {

String str = msgin.readLine();
text1.setText(str);

} catch(Exception e) {

text1.setText("Error" + e);

}
}
}
}

最佳答案

您尝试过推送通知吗?这是一个很好的起点 http://tokudu.com/2010/how-to-implement-push-notifications-for-android/

关于java - 如何在我的应用程序 android 中编写 StreamReader?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9143088/

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