Handler.postDelayed运行额外的时间 [英] Handler.postDelayed running for extra time

查看:853
本文介绍了Handler.postDelayed运行额外的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写的处理程序运行的固定量(30秒)的时间。基本的理由是它更新计数器绘制视图组件。

I am writing an handler to run for an fix amount(30 Sec) time. Basic on that it update counter to draw a view component.

counterRunnable = new Runnable() {
            int currV = 0;

            public void run(){

                if(count >= 360) {
                    counterHandler.removeCallbacks(this);
                    onTimerComplete();
                } else {
                    count++;
                    counterHandler.postDelayed(this, 83); // (30/360) = ~83
                }
            }
        };

由于我跑它的 83ms 360的时间延迟(83 * 360 = 29880ms〜30秒),但它正在运行的〜39秒。任何建议如果我做错什么。

As I am running back it for delay of 83ms for 360 time (83*360 = 29880ms ~30 Sec) but it is running for ~39 sec. Any suggestion if I am doing anything wrong.

分析: 我查了一下同<一href="http://developer.android.com/reference/java/util/Timer.html#scheduleAtFixedRate(java.util.TimerTask,%20long,%20long)"相对=nofollow>定时器(安排在固定利率),它的表现更好,因为比较<一个href="http://developer.android.com/reference/android/os/Handler.html#postDelayed(java.lang.Runnable,%20long)"相对=nofollow> Handler.postDelay 但还是任何建议为什么postDelay这里最糟糕

Analysis: I checked same with Timer(scheduled at fix rate) and it's performing better as compare Handler.postDelay but still any suggestion why postDelay worst here ?

推荐答案

您可以检查回答并实施这一行为与AlarmManager。

You can check this answer and implement this behaviour with AlarmManager.

正如你可以在<一见href="http://developer.android.com/reference/android/os/Handler.html#postDelayed(java.lang.Runnable,%20long)"相对=nofollow>文档,可以有一个额外的延迟可运行开始运行。你也可以检查从@CommonsWare这个解释:

As you can see in the documentation, there can be an additional delay for the runnable to start running. Also you can check this explanation from @CommonsWare:

Android是不是一个实时操作系统。所有postDelayed()   保证的是,这将是毫秒的至少数   指定。除此之外,这将是主要取决于什么主   应用程序线程正在做(如果你绑起来,它无法处理   Runnable接口),其次是对什么是要在设备上   (服务与后台优先级运行,因此得到较少的CPU时间   并不比前台)。

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

编辑:记住定时器创建您的code要执行的新线程。因此,它不依赖于主线程的工作量。您可以查看这里这讨论

Keep in mind that Timer creates a new thread for your code to be executed. So it doesn't depend on main thread's workload. You can check a discussion about this here

这篇关于Handler.postDelayed运行额外的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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