How to change screen brightness programmatically
This post will explain you how to change the current system brightness with a seek bar on Android devices. The application which we are going to develop will work only on real devices, because it is impossible to see the brightness changes on the emulator.
One thing you must know is that Android system brightness value is applied to the screen’s backlight only when the screen turns on. This means that only after a device boots up or awaking the phone from a sleeping state will make the screen as bright as the value defined by the System.SCREEN_BRIGHTNESS variable. Consequently, changing only that variable won’t be enough to preview the brightness level as the brightness value need to be set for the window.
[pgsubscribe]
That’s why it’s necessary to access the current window brightness by setting the screenBrightness property located at the LayoutParams object that is obtained from the current window. Then, we use the same value to set the system brightness and window brightness, so it can be previewed before its set.
Let us create simple application to demonstrate how we can change brightness of the system.
Quick Links
Project creation:
Project Structure
- Create new android project [File >> New >> Android Project] with project name AndroidBrightnessActivity
- Select target android device version [I chose version 2.2]
- Enter package name – ‘com.prgguru.example’
- Click finish
Code Listings
Layout XML:
Open layout XML present under /res/layout folder and replace the XML with the below one.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Slide the bar to change the brightness:" /> <SeekBar android:id="@+id/brightbar" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="30dip" android:layout_marginRight="30dip" > </SeekBar> </LinearLayout>
Application layout:
AndroidBrightnessActivity.java:
Open AndroidBrightnessActivity and replace the default code with below one. I hope the java code is self explanatory since each line is added with comments.
package com.prgguru.example; import android.app.Activity; import android.content.ContentResolver; import android.os.Bundle; import android.provider.Settings.SettingNotFoundException; import android.provider.Settings.System; import android.util.Log; import android.view.Window; import android.view.WindowManager.LayoutParams; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; public class AndroidBrightnessActivity extends Activity {//UI objects// //Seek bar object private SeekBar brightbar; //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; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //Instantiate seekbar object brightbar = (SeekBar) findViewById(R.id.brightbar); txtPerc = (TextView) findViewById(R.id.txtPercentage); //Get the content resolver cResolver = getContentResolver(); //Get the current window window = getWindow(); //Set the seekbar range between 0 and 255 brightbar.setMax(255); //Set the seek bar progress to 1 brightbar.setKeyProgressIncrement(1); try { //Get the current system brightness brightness = System.getInt(cResolver, System.SCREEN_BRIGHTNESS); } catch (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 brightbar.setProgress(brightness); //Register OnSeekBarChangeListener, so it can actually change values brightbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { public void onStopTrackingTouch(SeekBar seekBar) { //Set the system brightness using the brightness variable value System.putInt(cResolver, System.SCREEN_BRIGHTNESS, brightness); //Get the current window attributes 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 +" %"); } }); }}
Add WRITE_SETTINGS uses-permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_SETTINGS"></uses-permissi
Demo
Let us test the application:
Run click on the project >> Run as >> Android application
You could see following screens:
Download Source Code
Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse >> File >> Import.. >> Choose downloaded project(How to import android project in eclipse). If you just want to run the application in your mobile and see the output but don’t want to hit your head with source code, download application(apk) file and install it in your mobile device.
Download Source Code Download Application(apk)*apk in Android is the installation file simliar to exe in windows.
[pglinkadssmall]
I hope you enjoyed the post!! 🙂
[pgfeedback]
[pgwriteforus]