Changing the Screen Brightness System Setting Android
Asked Answered
P

4

18

I'm attempting to change the screen brightness from withing a service, like so:

android.provider.Settings.System.putInt(getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS, bright);

Problem is that is doesn't work. Well, actually it succeeds in changing the brightness setting, but the screen brightness doesn't actually change till I go into the phones settings, look at the new value and hit Ok.

Is there something I have to do after setting the value to get the brightness to change?

Paranoia answered 15/7, 2011 at 14:36 Comment(0)
T
42

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.

Typewrite answered 24/3, 2012 at 1:51 Comment(11)
Cool, I'll have to try this out when I get a chance.Paranoia
Works great. I made a small change in the style EmptyActivity <style name="EmptyActivity" parent="android:Theme.Dialog"> .... (same as posted by Anton Cherkashyn) <item name="android:windowBackground">@android:color/transparent</item> <item name="android:backgroundDimEnabled">false</item> <item name="android:windowIsFloating">true</item> </style>Ryley
PC, thank's for your comment, with your changes the brightness changing process is even more smooth.Typewrite
Instead of defining your own style, you can also just use android:theme="@android:style/Theme.Translucent" for your activity. Also, you can decrease the message delay to 500ms and it's still working.Pharr
...or Theme.Translucent.NoTitleBar if you don't like to see the title bar flashing up.Pharr
@AntonCherkashyn, thank you a million times. I have a bit different problem -- https://mcmap.net/q/332421/-how-to-turn-the-screen-on -- I took the liberty of copying & modifying your solution for the need of this particular task -- switching screen on (no brightness change). If you know some newer methods to solve this problem, please -- don't wait to respond :-).Limn
I am using this solution to turn on and off screen. It works for turning off (setting brightness to 0.0f ), but it doesnot turn on the screen(setting brightness to 1.0f). Is there any way to turn on screen?Hamill
@AntonCherkashyn I see you're not setting the layout, so why bother with styles.xml?Mccracken
@AntonCherkashyn +1 I just added approach with Handler and now it works, thanks buddy (without Handler it didn't work). So i assume that screen brightness refresh need some delay to be applied. Also invisible Activity is good catch! I used Theme.Translucent.NoTitleBar for my Activity.Rodarte
Add the following permissions declaration to the AndroidManifest.xml to make this work: <!-- Needed to write update to screen brightness --> <uses-permission android:name="android.permission.WRITE_SETTINGS" />Nepil
i want to change layoutParams.alpha for the system . Alpha is changing but as soon as the acivity is destroyed , it comes back to save value.Homans
L
6

I just checked in JB. The following code is enough to set brightness from a service

            android.provider.Settings.System.putInt(mContext.getContentResolver(), android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE, android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
            android.provider.Settings.System.putInt(mContext.getContentResolver(), android.provider.Settings.System.SCREEN_BRIGHTNESS, brightnessInt);

first line overrides the auto brightness.

Liger answered 11/4, 2013 at 19:8 Comment(1)
Its working fine and don't forget the permission <uses-permission android:name="android.permission.WRITE_SETTINGS"/>Ammoniac
D
0

You might have to do it through the Window object.

For example,

WindowManager.LayoutParams lp = getWindow().getAttributes();

lp.screenBrightness= lp.screenBrightness*1.25;

getWindow().setAttributes(lp);
Daguerre answered 15/7, 2011 at 14:41 Comment(1)
I'm running from within a service however, so I don't have a window to get.Paranoia
P
0

A less intrusive way (using significantly less code) is:

android.provider.Settings.System.putInt(getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS, bright);

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
pm.userActivity(SystemClock.uptimeMillis(), false);
Pitch answered 3/10, 2012 at 20:16 Comment(1)
The only problem is it does not change a thing.Limn

© 2022 - 2024 — McMap. All rights reserved.