Ich habe versucht, Timeout während der Ausführung von AsyncTask mehr als 1 Minute zu erstellen. Wenn die Zeit abgelaufen ist, sollte mit Notification beendet werden.Wie Timeout für AsyncTask-Ausführung festlegen?
Dies ist mein Code:
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();
}
}
Und das ist eine Klasse in doInBackground genannt, die Zeit bis zu setzen.
class TaskKiller extends TimerTask {
private AsyncTask<?, ?, ?> mTask;
public TaskKiller(AsyncTask<?, ?, ?> task) {
this.mTask = task;
}
public void run() {
mTask.cancel(true);
}
}
Aber wenn ich den Code ausführen, passiert nichts. Ich meine, der Fortschrittsdialog läuft immer sehr lange.
EDIT Ich habe meinen Code bearbeiten GetLongLat so etwas zu nennen:
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);
}
Aber auch nicht funktioniert.
http: // Stackoverflow.com/questions/7882739/android-setting-a-timeout-for-a-asynctask – Manifest