Search code examples
androidscreen-brightness

How to change brightness?


I run Runnable which should gradually change brightness

private Runnable runnable = new Runnable(){

        @Override
        public void run(){
            if(intensity < 1){ intensity += intensityGrow; }
            if(intensity > 1){ intensity = 1f; }
            Log.e("intensity", intensity + "/grow "+intensityGrow);

            android.provider.Settings.System.putInt(
                getContentResolver(),

                android.provider.Settings.System.SCREEN_BRIGHTNESS,(int)(255*intensity)
            );
            AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

            am.setStreamVolume(
                AudioManager.STREAM_ALARM, (int) (am.getStreamMaxVolume(AudioManager.STREAM_ALARM) * intensity), 0
            );
            if(intensity < 1){
                Log.e("intensity", "continue");

                handler.postDelayed(runnable, 1000);
            }

        }
    };

I also tried to use

        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.screenBrightness = intensity;
        getWindow().setAttributes(lp);

There is <uses-permission android:name="android.permission.WRITE_SETTINGS"/> in Manifest Also without result.


Solution

  • To make this work at first it is nessesarry to set brightness mode to manual

    Settings.System.putInt(
                            getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL
                        );
    

    Then change brightness using both methods

    android.provider.Settings.System.putInt(
                    getContentResolver(),
    
                    android.provider.Settings.System.SCREEN_BRIGHTNESS, (int) (255 * intensity)
                );
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.screenBrightness = intensity;
                getWindow().setAttributes(lp);