实现在Android的亮度逐渐衰落干净的方式?亮度、干净、方式、Android

2023-09-06 13:44:39 作者:落寞繁花,独我一人赏

目前,我有code褪色亮度的调整,看起来是这样的:

At the moment I have code to fade brightness adjustments which looks something like this:

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的,但我看不出在这种情况下,福利)。有没有更好的方式来实现背光衰落?

I'm not sure if that's considered good methodology (I considered using ASyncTask, but I can't see the benefits in this case). Is there a better way to achieve backlight fading?

编辑:我现在用的是TimerTask的如下:

I'm now using a TimerTask as follows:

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

我使用一个数组计数器的原因是因为它需要最后将在 Runnable接口访问,但我需要修改值。它会占用CPU少,但仍比我更喜欢。

The reason I use an array for the counter is because it needs to be final to be accessed in the Runnable, but I need to modify the value. This uses less CPU, but still more than I like.

EDIT2:Aaaand第三次尝试。感谢CommonsWare您的意见! (我希望我正确地运用它!)

Aaaand a third attempt. Thanks to CommonsWare for the advice! (I hope I applied it correctly!)

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

谢谢!

推荐答案

怎么样降低亮度的一半在每个迭代。

how about reducing the brightness to half in each iteration.

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

Then loop will complete in O(log n) rather than O(n) in current solution.