我一直试图在 AsyncTask 执行超过 1 分钟时创建超时。如果时间到了,则应该退出并通知。
这是我的代码:
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);
}
但是,也行不通。
最佳答案
我认为你可以使用 AsyncTask.get()
GetLongLat n = new GetLongLat();
n.get(30000, TimeUnit.MILLISECONDS);
你将不得不在一个单独的线程中使用 n.get..
已编辑:另一种不同但效率不高的方法。
GetLongLat n = new GetLongLat();
n.execute();
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
@Override
public void run() {
if ( n.getStatus() == AsyncTask.Status.RUNNING )
n.cancel(true);
}
}, 30000 );
关于android - 如何设置 AsyncTask 执行超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36245777/