Search code examples
androidandroid-activitysettingsbrightness

Best way to change a setting in activities from another one activity


I'm creating a simple ebook, but I need to change the screen brightness of some activities from my main activity, what receive a data from bluetooth and still running in background when book is running. My question is: How to call a function from MainActivity to Page1Activity, or the reverse, whatever.

if I put this code in one of the activities, I can change the activity brightness, but I really need to call that from one to another

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

If I use that one, the pages only will displays the changes when they are created, but I don't want to recreate a page whenever I receive a data.

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

android.provider.Settings.System.putInt(getContentResolver(),
        android.provider.Settings.System.SCREEN_BRIGHTNESS, (int)(255*adjusted));

Then I need to know if there is a way to get or store an activity to use the getWindow(), or if exists a way to call a function between two activities or if there is another way to do that.

PS: I know that function to change the volume, if I use that in the main activity, the audio of the whole system is changed instantly, if someone know an function to use in the brightness like that one, it would be the most simple way to solve my problem.

audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
        volAdjusted, AudioManager.FLAG_SHOW_UI);

Solution

  • At first add permission to your manifest file.

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

    Then you can change the brightness by running following lines of code:

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

    Note brightness must be an int value between 0 and 255.