在Android中固定时间后如何重复执行任务? [英] How to repeat a task after a fixed amount of time in android?

查看:736
本文介绍了在Android中固定时间后如何重复执行任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想每5秒重复调用一次方法,每当我希望停止该方法的重复调用时,我都可以停止或重新启动该方法的重复调用.

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);
}  

推荐答案

使用以下方法设置重复任务:

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);

,如果您想取消任务,只需调用t.cancel(),此处t是您的Timer对象

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.

这篇关于在Android中固定时间后如何重复执行任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆