문제

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!

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top