在Android中实现逐渐淡化亮度的清洁方式?

时间:2011-08-24 12:15:09

标签: android brightness fading

目前我有代码可以淡化亮度调整,如下所示:

new Thread() {
    public void run() {
        for (int i = initial; i < target; i++) {
            final int bright = i;
            handle.post(new Runnable() {
                public void run() {
                    float currentBright = bright / 100f;
                    window.getAttributes().screenBrightness = currentBright;
                    window.setAttributes(window.getAttributes());
                });
            }
            try {
                sleep(step);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}.start();

我不确定这是否被认为是好的方法(我考虑使用ASyncTask,但在这种情况下我看不到好处)。有没有更好的方法来实现背光衰落?

编辑:我现在正在使用TimerTask,如下所示:

new Timer().schedule(new TimerTask() {
    @Override
    public void run() {
        final float currentBright = counter[0] / 100f;
        handle.post(new Runnable() {    
            public void run() {
                window.getAttributes().screenBrightness = currentBright;
                window.setAttributes(window.getAttributes());
                if (++counter[0] <= target) {
                    cancel();
                }
            }
        });
    }
}, 0, step);

我为计数器使用数组的原因是因为需要在final中访问Runnable,但我需要修改该值。这使用较少的CPU,但仍然比我更喜欢。

EDIT2:Aaaand第三次尝试。感谢CommonsWare的建议! (我希望我正确应用它!)

    handle.post(new Runnable() {
        public void run() {
            if (counter[0] < target) {
                final float currentBright = counter[0] / 100f;
                window.getAttributes().screenBrightness = currentBright;            
                window.setAttributes(window.getAttributes());
                counter[0]++;
                handle.postDelayed(this, step);
            }
        }
   });

谢谢!

2 个答案:

答案 0 :(得分:2)

如何在每次迭代中将亮度降低一半。

然后循环将在O(log n)中完成而不是在当前解决方案中的O(n)。

答案 1 :(得分:1)