Reading, setting screen brightness in the app
PackageCom.catcher.testcompass;Importandroid.app.Activity;ImportAndroid.os.Bundle;Importandroid.provider.Settings;Importandroid.provider.Settings.SettingNotFoundException;ImportAndroid.provider.Settings.System;ImportAndroid.view.View;ImportAndroid.widget.EditText;ImportAndroid.widget.Toast; Public classThreeactivityextendsActivity {PrivateEditText etbrightness; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_third); Etbrightness=(EditText) Findviewbyid (R.ID.EDITTEXT1); } Public voidgetbrightness (view view) {Toast.maketext ( This, "brightness =" +getscreenbrightness (), Toast.length_short). Show (); } Public voidsetbrightness (view view) {intbrightness=Integer.parseint (Etbrightness.gettext (). toString ()); if(brightness>255) {Etbrightness.seterror ("No more than 255"); return; } setscreenbrightness (brightness); } Public voidSetscreenbrightness (intbrightness) { //If you are automatically adjusting the brightness, change to manual adjustment and then set the brightness Try { if(settings.system.screen_brightness_mode_automatic==Settings.System.getInt (Getcontentresolver (), System.screen_brightness_mode)) {Settings.System.putInt (Getcontentresolver (), System.screen_brightness_mode,system.screen_brightness_mode_ MANUAL); } } Catch(settingnotfoundexception e) {e.printstacktrace (); } Settings.System.putInt (Getcontentresolver (), system.screen_brightness, brightness); } Public intgetscreenbrightness () {intBrightness=-1; Try{Brightness=Settings.System.getInt (Getcontentresolver (), system.screen_brightness); } Catch(settingnotfoundexception e) {e.printstacktrace (); } returnbrightness; }}
Androidmanifest.xml also need to add permissions
<android:name= "Android.permission.WRITE_SETTINGS"/>
Layout file
<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"Android:keepscreenon= "true"android:orientation= "vertical" > <LinearLayoutAndroid:layout_width= "Match_parent"Android:layout_height= "Wrap_content"android:orientation= "Horizontal" > <EditTextAndroid:id= "@+id/edittext1"Android:layout_width= "0DP"Android:layout_weight= "1"Android:layout_height= "Wrap_content"Android:ems= "Ten"Android:hint= "Please enter an integer of 0-255"Android:inputtype= "Number" /> <ButtonAndroid:id= "@+id/button1"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:onclick= "Setbrightness"Android:text= "Set Brightness" /> </LinearLayout> <ButtonAndroid:id= "@+id/button2"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:onclick= "Getbrightness"Android:text= "Display Brightness" /></LinearLayout>
where android:keepscreenon= "true" can keep screen constants.
Read screen brightness, set screen brightness, maintain screen constants in Android apps