ACTION_SCREEN_ON and ACTION_SCREEN_OFF not working?

前端 未结 2 1443
青春惊慌失措
青春惊慌失措 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.

    0 讨论(0)
  • 2020-12-15 14:05

    To capture the SCREEN_OFF and SCREEN_ON actions (and maybe others) you have to configure the BroadcastReceiver by code, not through the manifest.

    IntentFilter intentFilter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
    BroadcastReceiver mReceiver = new ScreenStateBroadcastReceiver();
    registerReceiver(mReceiver, intentFilter);
    

    It's tested and works right.

    0 讨论(0)
提交回复
热议问题