Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clean way to implement gradual fading of brightness in Android?

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!

like image 599
Glitch Avatar asked Aug 24 '11 12:08

Glitch


1 Answers

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.

like image 155
MoveFast Avatar answered Sep 22 '22 15:09

MoveFast