作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我要开发一个从服务器接收消息的 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/
我是一名优秀的程序员,十分优秀!