我一直试图创建超时而AsyncTask执行超过1分钟。如果时间到了,那么应该退出通知。如何设置AsyncTask执行超时?
这是我的代码:
private class GetLongLat extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
longlatDialog = new ProgressDialog(MainActivity.this);
longlatDialog.setMessage("Fetching Data. Please wait..");
longlatDialog.setCancelable(false);
longlatDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
GPSTracker gpsTracker;
//This is the timer to set time out
Timer timer = new Timer();
timer.schedule(new TaskKiller(this), 3000);
timer.cancel();
do{
gpsTracker = new GPSTracker(MainActivity.this);
gpsTracker.getLocation();
}while(!String.valueOf(gpsTracker.latitude).equals("0.0"));
return null;
}
protected void onCancelled() {
// do something, inform user etc.
Toast.makeText(getApplicationContext(), "Failed getting long lat. Please check your internet connection", Toast.LENGTH_LONG).show();
System.exit(1);
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (longlatDialog.isShowing())
longlatDialog.dismiss();
}
}
这是一个名为doInBackground设置时间补课。
class TaskKiller extends TimerTask {
private AsyncTask<?, ?, ?> mTask;
public TaskKiller(AsyncTask<?, ?, ?> task) {
this.mTask = task;
}
public void run() {
mTask.cancel(true);
}
}
但是,当我运行的代码,没有发生。我的意思是进度对话总是运行很长时间。
编辑 我修改我的代码来调用GetLongLat是这样的:
GetLongLat n = new GetLongLat();
n.execute();
try {
n.get(3000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TimeoutException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "Failed getting long lat. Please check your internet connection", Toast.LENGTH_LONG).show();
System.exit(1);
}
而且,不能正常工作。
的http://计算器。com/questions/7882739/android-setting-a-timeout-for-an-asynctask – Manifest