How to adjust device brightness programmatically using SeekBar?

GChanna picture GChanna · Apr 23, 2016 · Viewed 7.4k times · Source

I have two seekbars in my settings application, one for sound and one for brightness. My sound seekbar does change the media volume as I want it to and it stays changed in other activities and applications but the brightness seekbar does not stay changed after I change the activity, it only changes the brightness in settings page. What I wish to accomplish is for both of them to stay as whatever I have set in the application settings page even in other activities and applications.

ApplicationSettings.java

public class ApplicationSettings extends AppCompatActivity {

private SeekBar VolumeSeekbar = null;
private SeekBar BrightnessSeekbar = null;
private AudioManager audioManager = null;
private float BackLightValue;
//Seek bar object
private SeekBar seekBar;
//Variable to store brightness value
private int brightness;
//Content resolver used as a handle to the system's settings
private ContentResolver cResolver;
//Window object, that will store a reference to the current window
private Window window;
TextView txtPerc;



@Override
public void onCreate(Bundle savedInstanceState) {
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_application_settings);

    //Instantiate seekbar object
    seekBar = (SeekBar) findViewById(R.id.BrightBar);
    txtPerc = (TextView) findViewById(R.id.txtPercentage);
    //Get the content resolver
    cResolver =  getContentResolver();
    //Get the current window
    window = getWindow();

    VolumeControl();
    BrightnessControl();
}


public void GoToMainScreenButton1 (View view) {
    Intent intentStart = new Intent(this, MainScreen.class);
    startActivity(intentStart);
}

private void VolumeControl() {
    try {
        VolumeSeekbar = (SeekBar) findViewById(R.id.SoundBar);
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        VolumeSeekbar.setMax(audioManager
                .getStreamMaxVolume(AudioManager.STREAM_MUSIC));
        VolumeSeekbar.setProgress(audioManager
                .getStreamVolume(AudioManager.STREAM_MUSIC));
        VolumeSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStopTrackingTouch(SeekBar arg0) {
            }
            @Override
            public void onStartTrackingTouch(SeekBar arg0) {
            }
            @Override
            public void onProgressChanged(SeekBar arg0, int progress, boolean arg2) {
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                        progress, 0);
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }

}

private void BrightnessControl() {
    //Set the seekbar range between 0 and 255
    //seek bar settings//
    //sets the range between 0 and 255
    seekBar = (SeekBar) findViewById(R.id.BrightBar);

    seekBar.setMax(255);
    //set the seek bar progress to 1
    seekBar.setKeyProgressIncrement(1);

    try
    {
        //Get the current system brightness
        brightness = Settings.System.getInt(cResolver, Settings.System.SCREEN_BRIGHTNESS);
    }
    catch (Settings.SettingNotFoundException e)
    {
        //Throw an error case it couldn't be retrieved
        Log.e("Error", "Cannot access system brightness");
        e.printStackTrace();
    }

    //Set the progress of the seek bar based on the system's brightness
    seekBar.setProgress(brightness);

    //Register OnSeekBarChangeListener, so it can actually change values
    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
    {
        public void onStopTrackingTouch(SeekBar seekBar)
        {
            //Set the system brightness using the brightness variable value
            Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS, brightness);
            //Get the current window attributes
            WindowManager.LayoutParams layoutpars = window.getAttributes();
            //Set the brightness of this window
            layoutpars.screenBrightness = brightness / (float)255;
            //Apply attribute changes to this window
            window.setAttributes(layoutpars);
        }
        public void onStartTrackingTouch(SeekBar seekBar)
        {
            //Nothing handled here
        }
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
        {
            //Set the minimal brightness level
            //if seek bar is 20 or any value below
            if(progress<=20)
            {
                //Set the brightness to 20
                brightness=20;
            }
            else //brightness is greater than 20
            {
                //Set brightness variable based on the progress bar
                brightness = progress;
            }
            //Calculate the brightness percentage
            float perc = (brightness /(float)255)*100;
            //Set the brightness percentage
            txtPerc.setText((int)perc +" %");
        }
    });
}
}

activity_application_settings.xml

<!--        android:background="#000000"-->

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text=" Adjust the Sound volume"
    android:id="@+id/SOUNDTEXT"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_marginTop="87dp" />

<SeekBar
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/SoundBar"
    android:background="#87CEEB"
    android:layout_gravity="center_vertical"
    android:layout_alignParentStart="true"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/SOUNDTEXT"
    android:layout_alignRight="@+id/Mainbutton11"
    android:layout_alignEnd="@+id/Mainbutton11" />

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text=""
    android:id="@+id/SoundPercentage"
    android:background="#87CEEB"
    android:layout_alignBottom="@+id/SoundBar"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_toRightOf="@+id/SoundBar"
    android:layout_toEndOf="@+id/SoundBar" />

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text=" Adjust the Brightness"
    android:id="@+id/textView18"
    android:layout_above="@+id/BrightBar"
    android:layout_toStartOf="@+id/Mainbutton11"
    android:layout_toLeftOf="@+id/Mainbutton11"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />

<SeekBar
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/BrightBar"
    android:background="#87CEEB"
    android:layout_gravity="left|bottom"
    android:layout_centerVertical="true"
    android:layout_toLeftOf="@+id/SoundPercentage"
    android:layout_toStartOf="@+id/SoundPercentage" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/txtPercentage"
    android:layout_alignTop="@+id/BrightBar"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_alignLeft="@+id/SoundPercentage"
    android:layout_alignStart="@+id/SoundPercentage" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Go to chapters"
    android:background="#FFE4B5"
    android:onClick="GoToMainScreenButton1"
    android:id="@+id/Mainbutton11"
    android:layout_gravity="center_horizontal|top"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true" />

Answer

user1626594 picture user1626594 · Apr 23, 2016

Are you handling the automatic brightness mode?

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

Also do you have the manifest permission?

<uses-permission android:name="android.permission.WRITE_SETTINGS"></uses-permission>

PS: I'd comment these questions but can't comment yet sorry.