Reputation: 1501
I have created an asynctask to show progress dialog while ghetting the users location. I want to run this asynctask for 30 seconds and if in these 30 seconds I haven't found the users location I would like just to kill the task and show an error message.
My code so far is like this:
userLocation = new AsyncTask<Void, Void, Void>() {
private ProgressDialog locationDialog = new ProgressDialog(MainActivity.this);
@Override
protected void onPreExecute() {
super.onPreExecute();
locationDialog.setMessage(getResources().getString(R.string.getting_location));
locationDialog.setCancelable(false);
locationDialog.setIndeterminate(true);
locationDialog.show();
}
@Override
protected Void doInBackground(Void... params) {
try {
latitude = locationProvider.getLatitude();
longitude = locationProvider.getLongitude();
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// getLocation.cancel(true);
if (latitude != 0 && longitude != 0) {
locationDialog.dismiss();
getData();
} else {
locationDialog.dismiss();
alertDialog.show();
Log.d("Couldn't get location", "Couldn't get location");
}
}
};
userLocation.execute((Void[])null);
How should I edit my code so that if the latitude and longitude after 30 seconds is 0, just kill the asynctask and show some kind of error message. Any ideas?
Upvotes: 3
Views: 6593
Reputation: 1141
You should make a handler which cancels the Asynctask (http://developer.android.com/reference/android/os/AsyncTask.html#cancel(boolean))
Send a delayed message to this Handler like:
Handler.sendMessageDelayed(msg, delayMillis)
private android.os.Handler mHandler = new android.os.Handler() {
@Override
public void handleMessage(Message msg) {
(Your AsyncTask object).cancel(true);
}
}
Upvotes: 5