3

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?

3
  • stackoverflow.com/questions/16538714/…. Commented Aug 4, 2013 at 18:05
  • But how can I set the time, for example, if after 30 seconds the latidue = 0 only then cancle the task? Commented Aug 4, 2013 at 18:19
  • use a handler or a timer task instead of asynctask. Commented Aug 4, 2013 at 18:20

1 Answer 1

5

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);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.