Tuesday, March 20, 2012

Android: Timer/TimerTask/Hander/ stopping AsyncTask

Here's a common implementation that I used.

The Handler and TimerTask that is randomly within my activity class.

private Handler mHandler = new Handler();
 private class MyTimerTask extends TimerTask {
  @Override
  public void run() {
   mHandler.post(new Runnable() {
    @Override
    public void run() {
     Log.i("MyTimerTask", "Cancelling Search Task");
     progressBarLayout.setVisibility(LinearLayout.INVISIBLE);
     if (!stask.isCancelled()) stask.cancel(true);
     toast = Toast.makeText(mContext,"Could not find any locations", Toast.LENGTH_LONG);
     toast.show();
    }
   });
  }
  
 }


I have a Timer global variable in the AsyncTask class, so then I instantiate the timer and run it like this within the Async doInBackground method:

timer = new Timer();
timer.schedule(new MyTimerTask(), SEARCH_TIME_OUT);

In the post execute method, I cancelled the timer. Not sure if the timer will still be running after the AsyncTask is done, so I cancelled it just in case.

In the doInBackground, I could've handled all the code in one section without creating any classes in the activity. So it would've looked like this:

final Handler mHandler = new Handler();
TimerTask mTimerTask = new TimerTask() {
   public void run() {
      mHandler.post(new Runnable() {
          //handle cancelling here
   });
};
mTimer = new Timer();
mTimer.schedule(mTimerTask, TIME_OUT);

Hmmm, this seems better to use. I'll switch that in my code later.

No comments:

Post a Comment