我有一个套接字客户端,用于从服务器接收数据。在模拟器中一切正常,但是在我的 android 上,消息总是滞后一个,因此我的 GUI 没有用新数据更新。
涉及的代码(客户端在 Asynctask 中运行)
@Override
protected Boolean doInBackground(Void... params) { //This runs on a different thread
try {
Log.i("AsyncTask", "doInBackground: Creating socket");
SocketAddress sockaddr = new InetSocketAddress("192.168.x.xxx", 9090);
nsocket = new Socket();
nsocket.connect(sockaddr, 5000); //10 second connection timeout
if (nsocket.isConnected()) {
in = new BufferedReader(new InputStreamReader(nsocket.getInputStream()));
wr = new BufferedWriter(new OutputStreamWriter(nsocket.getOutputStream()));
Log.i("KMC.AsyncTask", "doInBackground: Socket created, streams assigned");
sockState = true;
String inputLine = "";
while ((inputLine = in.readLine()) != null) {
result = inputLine.replace("\\","");
Log.d("KMC", "Got some data: " + result);
this.publishProgress(1);
}
}
} catch (IOException e) {
e.printStackTrace();
Log.i("KMC.AsyncTask", "doInBackground: IOException");
} catch (Exception e) {
e.printStackTrace();
Log.i("KMC.AsyncTask", "doInBackground: Exception");
} finally {
try {
nis.close();
wr.close();
nsocket.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Log.i("KMC.AsyncTask", "doInBackground: Finished");
}
return true;
}
protected void onProgressUpdate(Integer... values) {
try {
JSONObject jObject = new JSONObject(result.substring(1, result.length()-1));
if(jObject.getString("type").equals("event")){
EventHandler.newEvent(jObject.getString("name"), jObject.getJSONArray("data"));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
我试图在谷歌上找到解决方案,但我找不到任何东西。