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

Gli*_*tch 11 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();
Run Code Online (Sandbox Code Playgroud)

我不确定这是否被认为是好方法论(我考虑过使用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);
Run Code Online (Sandbox Code Playgroud)

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

编辑2: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);
            }
        }
   });
Run Code Online (Sandbox Code Playgroud)

谢谢!

Mov*_*ast 2

在每次迭代中将亮度降低一半怎么样?

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