How to detect if screen brightness has changed in Android?

[亡魂溺海] 提交于 2019-12-13 15:28:00

问题


I have searched extensively and couldn't find a similar question.

I would like to know if there is any way to detect when the screen brightness of a mobile device has been changed.

I have already tried to store the old value when the app starts and repeatedly check usingSettings.System.getInt(getContentResolver(),Settings.System.SCREEN_BRIGHTNESS); to compare the initial and final value of screen brightness , which is not a good way of doing so.

Thanks

EDIT: This question states that I have already tried the solution of using Settings.System.SCREEN_BRIGHTNESS to get current screen values and periodically check for screen brightness changes. I am looking for a more efficient way of doing such an operation.


回答1:


There are no receivers provided to detect brightness change.

You have to run a Service or Thread to check the brightness change by yourself.

Settings.System.getInt(getContext().getContentResolver(), 
             Settings.System.SCREEN_BRIGHTNESS);

The above code will give you current system brightness level. Periodically detect the brightness and compare with the old one.

Note: If the system is in Auto Brightness mode, you can't get current brightness level. See this answer.




回答2:


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)
    
  • permission in AndroidManifest.xml:

    <uses-permission android:name="android.permission.WRITE_SETTINGS"/>
    
  • for API >= 23, you need to request the permission through Settings Activity

other useful links:

  • ContentObserver onChange
  • Change the System Brightness Programmatically


来源:https://stackoverflow.com/questions/46119279/how-to-detect-if-screen-brightness-has-changed-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!