Handling Screen OFF and Screen ON Intents

不像其他广播包,Intent.ACTION_SCREEN_OFF 和Intent.ACTION_SCREEN_ON不能在manifest中申明,需要用代码注册。

Receiver代码如下:

public class ScreenReceiver extends BroadcastReceiver {

// thanks Jason
public static boolean wasScreenOn = true;

@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// do whatever you need to do here
wasScreenOn = false;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// and do whatever you need to do here
wasScreenOn = true;
}
}

}


例子activity如下:

public class ExampleActivity extends Activity {

@Override
protected void onCreate() {
// initialize receiver
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
// your code
}

@Override
protected void onPause() {
// when the screen is about to turn off
if (ScreenReceiver.wasScreenOn) {
// this is the case when onPause() is called by the system due to a screen state change
System.out.println("SCREEN TURNED OFF");
} else {
// this is when onPause() is called when the screen state has not changed
}
super.onPause();
}

@Override
protected void onResume() {
// only when screen turns on
if (!ScreenReceiver.wasScreenOn) {
// this is when onResume() is called due to a screen state change
System.out.println("SCREEN TURNED ON");
} else {
// this is when onResume() is called when the screen state has not changed
}
super.onResume();
}

}


参见:

Handling Screen OFF and Screen ON Intents

android.intent.action.SCREEN_ON doesn't work as a receiver intent filter


你可能感兴趣的:(intent)