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
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.
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.