user2391890 user2391890 - 1 month ago 7
Java Question

How to repeat a task after a fixed amount of time in android?

I want to repeatedly call a method after every 5-seconds and whenever I wish to to stop the repeated call of the method I may stop or restart the repeated call of the method.

Here is some sample code that whats really I want to implement. Please help me in this respect I would be very thankful to you.

private int m_interval = 5000; // 5 seconds by default, can be changed later
private Handler m_handler;

@Override
protected void onCreate(Bundle bundle)
{
...
m_handler = new Handler();
}

Runnable m_statusChecker = new Runnable()
{
@Override
public void run() {
updateStatus(); //this function can change value of m_interval.
m_handler.postDelayed(m_statusChecker, m_interval);
}
};

public void startRepeatingTask()
{
m_statusChecker.run();
}

public void stopRepeatingTask()
{
m_handler.removeCallbacks(m_statusChecker);
}

Gru Gru
Answer

Set repeated task using this:

//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {

    @Override
    public void run() {
        //Called each time when 1000 milliseconds (1 second) (the period parameter)
    }

},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
1000);

and if you wanted to cancel the task simply call t.cancel() here t is your Timer object

and you can also check comment placed below your answer they have given brief information about that.