ACTION_SCREEN_ON and ACTION_SCREEN_OFF not working?

前端 未结 2 1444
青春惊慌失措
青春惊慌失措 2020-12-15 13:38

I\'m trying to turn WiFi off when the screen is OFF (locked), and turn it on again when screen is ON (unlocked).

I made a BroadcastReceiver; put in mani

2条回答
  •  爱一瞬间的悲伤
    2020-12-15 13:51

    You cannot catch those intents through XML (I forget why). However, you could use a Service that registers a BroadcastReceiver member in its onStartCommand() and unregisters it in its onDestroy(). This would require the service to be running in the background, constantly or as long as you need it to, so be sure to explore alternative routes.

    You could define the BroadcastReceiver in your Service class like so:

    private final class ScreenReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(final Context context, final Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                 //stuff
            } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
                 //other stuff
            }
        }
    }
    

    For a slightly complicated example, but one that shows how the BroadcastReceiver and Service interact see CheckForScreenBugAccelerometerService from my app, ElectricSleep.

提交回复
热议问题