11

現時点では、次のような明るさ調整をフェードするコードがあります。

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 の使用を検討しましたが、この場合の利点はわかりません)。バックライトのフェードを実現するためのより良い方法はありますか?

編集:私は現在、次のように 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);

カウンターに配列を使用する理由は、finalでアクセスする必要Runnableがあるためですが、値を変更する必要があります。これは CPU の使用量を減らしますが、それでも私が好む以上に使用します。

EDIT2:ああ、そして3回目の試み。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);
            }
        }
   });

ありがとう!

4

2 に答える 2

2

各反復で明るさを半分に減らすのはどうですか。

次に、ループは、現在のソリューションでは O(n) ではなく O(log n) で完了します。

于 2011-09-15T15:47:58.293 に答える
1

Honeycomb から、Property Animationを使用してこれを行うことができます。Android Developers ブログのこの投稿では、すべてについて詳しく説明しています

于 2011-09-15T16:01:11.367 に答える