public class VisitTask extends AsyncTask<Void, Integer, Boolean> {
private UserSocket userSocket;
private TextView visitView;
private Context context;
启动AsyncTask
public VisitTask(UserSocket userSocket, TextView visitView, Context context) {
this.userSocket = userSocket;
this.visitView = visitView;
this.context = context;
}
@Override
protected void onPreExecute() {
visitView.setText(null);
}
doInBackgroud ...访问图表中的房间
@Override
protected Boolean doInBackground(Void... params) {
ClientSocket clientSocket = userSocket.getcSocket();
Integer i = 0;
ArrayList<Integer> rooms = new ArrayList<>();
while (!isCancelled()) {
try {
publishProgress(i);
rooms = clientSocket.visitGraph(i);
} catch (IOException e) {
e.printStackTrace();
}
i = rooms.get((int) (rooms.size() * Math.random()));
if (i == 16) {
break;
}
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return clientSocket.close();
}
尝试使用访问室的数量实时更新textview。
@Override
protected void onProgressUpdate(Integer... values) {
//Integer currentRoom = values[0];
/*ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageDrawable(getDrawable(R.drawable.s1));*/
// TextView visitView = (TextView) findViewById(R.id.VisitView);
visitView.append(String.format("You're visiting " + values[0] + " " + DateFormat.getDateTimeInstance().format(new Date())) + '\n');
}
}
出乎意料的是,在AsyncTask结束时,一次性调用onProgressUpdate方法。 有人可以帮帮我吗? 在使用套接字连接进行日志记录后,我在这里调用它。
MyClientTask myClientTask = new MyClientTask(ip, args);
myClientTask.execute();
UserSocket userSocket = myClientTask.get();
if (userSocket.getBoolean()) {
new Toast(getApplicationContext()).makeText(getApplicationContext(), "Login successfully", Toast.LENGTH_SHORT).show();
VisitTask visitTask = new VisitTask(userSocket, visitView, getApplicationContext());
visitTask.execute();
if (visitTask.get()) {
new Toast(getApplicationContext()).makeText(getApplicationContext(), "You've completed your visit", Toast.LENGTH_SHORT).show();
}