4

How to schedule a function every defined time with the option to change this time? I found that I can do it using timer & timerTask or handler. The problem that it dosen't repeats the time I defined, it repeats randomaly...

    runnable = new Runnable() {

        @Override
        public void run() {
            //some action
            handler.postDelayed(this, interval);
        }
    };

            int hours = settings.getIntervalHours();
            int minutes = settings.getIntervalMinutes();

            long interval = (hours * 60 + minutes) * 60000;

            changeTimerPeriod(interval);

private void changeTimerPeriod(long period) {
    handler.removeCallbacks(runnable);
    interval = period;
    runnable.run();
}
Alex K
  • 5,092
  • 15
  • 50
  • 77

2 Answers2

12

Use a Handler object in the onCreate method. Its postDelayed method causes the Runnable parameter to be added to the message queue and to be run after the specified amount of time elapses (that is 0 in given example). Then this will queue itself after fixed rate of time (1000 millis in this example).

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    android.os.Handler customHandler = new android.os.Handler();
    customHandler.postDelayed(updateTimerThread, 0);
}

private Runnable updateTimerThread = new Runnable()
{
    public void run()
    {
        //write here whaterver you want to repeat
        customHandler.postDelayed(this, 1000);
    }
};
Massimiliano Kraus
  • 3,638
  • 5
  • 27
  • 47
Gazal Patel
  • 480
  • 5
  • 10
3

I used the solution here

But in the code where the handler was initialized, I used

mHandler = new Handler(getMainLooper);

instead of

mHandler = new Handler();

which worked for me

Community
  • 1
  • 1
Tahmid Rahman
  • 748
  • 1
  • 8
  • 20