我在我的 AsyncTask
中运行一个套接字客户端。我需要找到一种方法来调用外部发送。例如:socketClient.send(msg);
SocketClient
是在 service
中定义的。当 UI 发送一个 broadcast
并且 service 接收
它时,将调用 Send。到目前为止,我所有的尝试都导致应用程序崩溃。
这是我的代码:
public class SocketClient extends AsyncTask<Void, Void, Void> {
private String ip;
private int port;
private Socket socket = null;
private BufferedReader in = null;
private PrintWriter out = null;
private boolean connected;
String devID;
public SocketClient(String ip, int port, String devID){
this.ip = ip;
this.port = port;
this.devID = devID;
connected = true;
}
@Override
protected Void doInBackground(Void... arg0){
try{
socket = new Socket(ip, port);
} catch(Exception ex){
socket = null;
}
try{
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
send(new SocketMessage("ident", "sdas", "", ""));
while(connected) {
SocketMessage msg = new SocketMessage(in.readLine());
handle(msg);
}
//clean up
out.println(new SocketMessage("quit", "","", ""));
out.flush();
} catch(Exception ex){
ex.printStackTrace();
}
finally{
try{
connected = false;
out.close();
in.close();
socket.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
return null;
}
public void handle(SocketMessage msg){
}
public synchronized void send(SocketMessage msg){
out.println(msg.getJSON());
out.flush();
}
}
最佳答案
AsyncTask
不是为长时间运行的进程设计的。在那种情况下,您最好使用 Thread
。请参阅 Connecting Techniques 的开发人员指南.
关于android - 与 Android 中的 AsyncTask 通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45520199/