Handler postDelayed delayed longer as configured

时光毁灭记忆、已成空白 提交于 2019-12-01 12:32:40

问题


I try to develop a simple timer beeper, that peep hourly. For the timing I use a Service and handler, here the example:

    void onStart(...){
        handler.postDelayed(timerRunnable, ONE_HOUR);
    }

    private Runnable timerRunnable = new Runnable() {

    @Override
        public void run() {
               ...beep
               handler.postDelayed(timerRunnable, ONE_HOUR);
        }
    };

but run() method will be fired nondeterministic, I think it is dependent from the current device usage.

I have try the same scenario with TimerTask and with 'manualy' Thread implementation, but with the same nondeterministic result.


回答1:


You'll probably have better luck using the AlarmManager for such a long delay. Handler is best for ticks and timeouts while your app is in the foreground.

http://developer.android.com/reference/android/app/AlarmManager.html




回答2:


Android is not a real-time operating system. All postDelayed() guarantees is that it will be at least the number of milliseconds specified. Beyond that will be dependent primarily on what the main application thread is doing (if you are tying it up, it cannot process the Runnable), and secondarily on what else is going on the device (services run with background priority and therefore get less CPU time than does the foreground).



来源:https://stackoverflow.com/questions/5824912/handler-postdelayed-delayed-longer-as-configured

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!