1

Inside my Android code, I'm responding to a button press by calling Timer.schedule(myTask,0,1000), which calls myTimerTask::run(), which is something like this:

nested within my Activity:

class mytimerTask extends TimerTask {
    @Override
    public void run() {
        //update my progress bar
        //if progress bar is full, i want to call a function that is in my activity
    }
}

Can I straight up reference one of my Activity methods from TimerTask? It seems to crash the app when I try it.

Would it be better for me to handle my ProgressBar and eventual execution of code from a Runnable instead of a Timer/TimerTask?

Brianide
  • 461
  • 1
  • 6
  • 17

1 Answers1

1

You need to yor code as follow. To know reason check following thread What is the Android UiThread (UI thread) or http://developer.android.com/resources/articles/painless-threading.html

   Timer t;
   Handler handler = new Handler();


t = new Timer();
Class MyTimerTask extends TimerTask{
    public void run() {
            handler.post(new Runnable() {
                    public void run() {
                        //update my progress bar
    //if progress bar is full, i want to call a function that is in my activity

                    }
           });
    }

    t.schedule(timeTask, 0, 1000);
Community
  • 1
  • 1
Vivek
  • 4,170
  • 6
  • 36
  • 50
  • 1
    So you're saying if I declare it like this as an actual TimerTask with a defined run(), it should work out instead of extending TimerTask like I am? – Brianide Oct 13 '11 at 03:17
  • No don't want say that, I wan't to say that if you are trying to update UI of activity it should be done from UI thread. – Vivek Oct 13 '11 at 06:31
  • Worked great! Now I gotta figure out why calling MyTimerTask twice crashes the app, but the timer and firing of the function is perfect. Thanks! – Brianide Oct 14 '11 at 02:09