I am working on an android application which changes the screen brightness programmatically. I have a set brightness method which works on 5.1.1,But when i run the application on 6.0,it gives an error and closes the application. Please Help.
Following is my approach:
public void setBrightness(View view,int brightness){
//Just a loop for checking whether the brightness changes
if(brightness <46)
brightness = 255;
else if(brightness >150)
brightness=45;
ContentResolver cResolver = this.getApplicationContext().getContentResolver();
Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS, brightness);
}
public void setDisplay(View view)
{
ContentResolver cResolver = getContentResolver();
Window window = getWindow();
int brightness=0;
try
{ Settings.System.putInt(cResolver,Settings.System.SCREEN_BRIGHTNESS_MODE
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
brightness = Settings.System.getInt(cResolver, Settings.System.SCREEN_BRIGHTNESS);
System.out.println("Current Brightness level " + brightness);
}
catch (Exception e)
{
Log.e("Error", "Cannot access system brightness");
e.printStackTrace();
}
setBrightness(view,brightness);
}
Apparently you need to explicitly ask the user for permission on devices running Android 6.0+.
Try the following code: (I have modified it for you)
@TargetApi(Build.VERSION_CODES.M)
public void setBrightness(View view,int brightness){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (Settings.System.canWrite(getApplicationContext()))
{
if (brightness < 46)
brightness = 255;
else if (brightness > 47)
brightness = 0;
ContentResolver cResolver = this.getApplicationContext().getContentResolver();
Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS, brightness);
} else
{
Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
intent.setData(Uri.parse("package:" + this.getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
Note that you need the WRITE_SETTINGS permission in your manifest, also.