Clean way to implement gradual fading of brightness in Android?

人走茶凉 提交于 2019-12-05 16:42:56

问题


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

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?

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

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

Thanks!


回答1:


how about reducing the brightness to half in each iteration.

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




回答2:


From Honeycomb you can do things lie this using Property Animation. This post on the Android Developers blog talks about it all in some detail.



来源:https://stackoverflow.com/questions/7175233/clean-way-to-implement-gradual-fading-of-brightness-in-android

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