public class MyClientTask extends AsyncTask<String, String, String> {
String dstAddress;
int dstPort;
MyClientTask(String addr, int port) {
dstAddress = addr;
dstPort = port;
}
protected String doInBackground(String... arg0) {
String response = "";
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
BufferedReader stdIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while ((response = stdIn.readLine()) != null) {
Log.i("response", response);
publishProgress(response);
}
Log.i("response", response);
} catch (UnknownHostException e) {
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
e.printStackTrace();
response = "IOException: " + e.toString();
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
protected void onProgressUpdate(String... values) {
Log.i("prama", values[0]);
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
super.onPostExecute(result);
}
}
我编写上面的代码来从socket读取值。当我启动异步任务时,值将在日志中打印,就像在doInbackground中一样,但是在异步任务完成后我的toast消息不会被触发。