Changing the Screen Brightness System Setting Android

Changing the Screen Brightness System Setting Android

I've had the same problem of changing screen brightness from within a service, and a couple days ago i have successfully solved it(and updated my app Phone Schedule with brightness feature ;) ).
Ok, so this is the code you put into your service:

// This is important. In the next line 'brightness' 
// should be a float number between 0.0 and 1.0
int brightnessInt = (int)(brightness*255);

//Check that the brightness is not 0, which would effectively
//switch off the screen, and we don't want that:
if(brightnessInt<1) {brightnessInt=1;}

// Set systemwide brightness setting.
Settings.System.putInt(getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, brightnessInt);

// Apply brightness by creating a dummy activity
Intent intent = new Intent(getBaseContext(), DummyBrightnessActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("brightness value", brightness);
getApplication().startActivity(intent);

Please Note that in the above code snippet I'm using two variables for brightness. One is brightness, which is a float number between 0.0 and 1.0, the other one is brightnessInt, which is an integer between 0 and 255. The reason for this is that Settings.System requires an integer to store system wide brightness value, while the lp.screenBrightness which you will see in the next code snippet requires a float. Don't ask me why not use the same value, this is just the way it is in Android SDK, so we're just going to have to live with it.

This is the code for DummyBrightnessActivity:

public class DummyBrightnessActivity extends Activity{

private static final int DELAYED_MESSAGE = 1;

private Handler handler;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if(msg.what == DELAYED_MESSAGE) {
DummyBrightnessActivity.this.finish();
}
super.handleMessage(msg);
}
};
Intent brightnessIntent = this.getIntent();
float brightness = brightnessIntent.getFloatExtra("brightness value", 0);
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = brightness;
getWindow().setAttributes(lp);

Message message = handler.obtainMessage(DELAYED_MESSAGE);
//this next line is very important, you need to finish your activity with slight delay
handler.sendMessageDelayed(message,1000);
}

}

This is how you add your activity to the AndroidManifest.xml, probably the most important part:

<activity android:name="com.antonc.phone_schedule.DummyBrightnessActivity"
android:taskAffinity="com.antonc.phone_schedule.Dummy"
android:excludeFromRecents="true"
android:theme="@style/EmptyActivity"></activity>

A little explanation about what's what.

android:taskAffinity must be different, than your package name! It makes DummyBrightnessActivity be started not in your main stack of activities, but in a separate, which means that when DummyBrightnessActivity is closed, you won't see the next activity, whatever that may be. Until i included this line, closing DummyBrightnessActivity would bring up my main activity.

android:excludeFromRecents="true" makes this activity not available in the list of recently launched apps, which you definetely want.

android:theme="@style/EmptyActivity" defines the way DummyBrightnessActivity looks like to the user, and this is where you make it invisible. This is how you define this style in the styles.xml file:

<style name="EmptyActivity" parent="android:Theme.Dialog">
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowAnimationStyle">@android:style/Animation.Toast</item>
<item name="android:background">#00000000</item>
<item name="android:windowBackground">#00000000</item>
<item name="android:windowNoTitle">true</item>
<item name="android:colorForeground">#000</item>
</style>

This way your DummyBrightnessActivity will be invisible to the user. I'm not shure if all of those style parameters are really necessary, but it works for me this way.

I hope that explains it, but if you have any questions, just let me know.

android - Setting the screen brightness to maximum level

You can use this

public class MainActivity extends AppCompatActivity {

private int brightness=255;
//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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

cResolver = getContentResolver();

//Get the current window
window = getWindow();

try
{
// To handle the auto

Settings.System.putInt(cResolver,
Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
//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();
}

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)100;
//Apply attribute changes to this window
window.setAttributes(layoutpars);
}
}

And the most important permission in the manifest

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

Asking for Write Settings permission in API 23

private boolean checkSystemWritePermission() {
boolean retVal = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
retVal = Settings.System.canWrite(this);
Log.d(TAG, "Can Write Settings: " + retVal);
if(retVal){
Toast.makeText(this, "Write allowed :-)", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this, "Write not allowed :-(", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
intent.setData(Uri.parse("package:" + getActivity().getPackageName()));
startActivity(intent);
}
}
return retVal;
}

Android Development: Changing Screen Brightness in Service

A service cannot change the screen brightness that way. A service does not have a user interface, so it does not have Window.

You can try to change the brightness system-wide via the SCREEN_BRIGHTNESS system setting. I have no idea if this works, as I have not tried it.

Otherwise, modify your activities to change their brightness.

Changing Screen brightness in 6.0 programmatically

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.

Can't apply system screen brightness programmatically in Android

OK, found the answer here:
Refreshing the display from a widget?

Basically, have to make a transparent activity that processes the brightness change. What's not mentioned in the post is that you have to do:

Settings.System.putInt(y.getContentResolver(),Settings.System.SCREEN_BRIGHTNESS_MODE, 0);
Settings.System.putInt(y.getContentResolver(),Settings.System.SCREEN_BRIGHTNESS, brightnessLevel);

then do

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

And if you call finish() right after applying the changes, brightness will never actually change because the layout has to be created before the brightness settings is applied. So I ended up creating a thread that had a 300ms delay, then called finish().

How to detect if screen brightness has changed in Android?

yes, there is a way by using ContentObserver:

  • code:

      // listen to the brightness system settings
    val contentObserver = object:ContentObserver(Handler())
    {
    override fun onChange(selfChange:Boolean)
    {
    // get system brightness level
    val brightnessAmount = Settings.System.getInt(
    contentResolver,Settings.System.SCREEN_BRIGHTNESS,0)

    // do something...
    }
    }

    // register the brightness listener upon starting
    contentResolver.registerContentObserver(
    Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS),
    false,contentObserver)

    // .....

    // unregister the listener when we're done (e.g. activity destroyed)
    contentResolver.unregisterContentObserver(contentObserver)

other useful links:

  • what thread is ContentObserver.onChange called on?
  • Change the System Brightness Programmatically

How do you set brightness of screen in Android?

You can use this API. This will change screen brightness of your window and not of the whole system.

        // Make the screen full bright for this activity.
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = 1.0f;

getWindow().setAttributes(lp);


Related Topics



Leave a reply



Submit