【问题标题】:android - How to repeat a function every contant time?android - 如何每隔一段时间重复一个功能?
【发布时间】:2013-01-12 11:09:11
【问题描述】:

如何在每个定义的时间安排一个函数,并可以选择更改这个时间? 我发现我可以使用 timer & timerTask 或处理程序来做到这一点。它不重复我定义的时间的问题,它随机重复......

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

【问题讨论】:

  • 可以使用Handler。你可能会得到你的精确解决方案here

标签: android repeat


【解决方案1】:

onCreate 方法中使用Handler 对象。它的postDelayed 方法导致Runnable 参数被添加到消息队列并在经过指定的时间量后运行(在给定示例中为0)。然后这将在固定的时间速率(本例中为 1000 毫秒)后自行排队。

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

【讨论】:

  • @MarkBuikema 泄漏在哪里?能不能说的具体点?
  • 内存泄漏可能是错误的术语,但是当应用程序暂停时这种情况会继续(我认为这不是您想要的)。
【解决方案2】:

我使用了here的解决方案

但是在初始化处理程序的代码中,我使用了

mHandler = new Handler(getMainLooper);

而不是

mHandler = new Handler();

这对我有用

【讨论】:

    猜你喜欢
    • 2012-07-03
    • 2016-12-24
    • 2015-10-12
    • 1970-01-01
    • 1970-01-01
    • 2015-08-14
    • 2013-02-19
    • 1970-01-01
    • 2019-04-29
    相关资源
    最近更新 更多