Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android - How to repeat a function every contant time?

Tags:

android

repeat

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();
}
like image 634
Alex Kapustian Avatar asked Dec 12 '22 18:12

Alex Kapustian


1 Answers

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);
    }
};
like image 141
Gazal Patel Avatar answered Jan 05 '23 18:01

Gazal Patel