监听ACTION_SCREEN_OFF

我试图启动一个服务,在侦听ACTION_SCREEN_OFF的后台运行,当它发现ACTION_SCREEN_OFF ,启动我的活动。

我读了一个地方,你需要创build一个BroadcastReceiver,因为把它放在清单XML不起作用。 但是,我不知道从哪里开始,经过多次search。

您不能在AndroidManifest.xml中声明ACTION_SCREEN_ONACTION_SCREEN_OFF 。 只有在您的活动正在运行时,您才被允许捕捉它们。

这是一个例子。

BroadcastReceiver

 public class ScreenReceiver extends BroadcastReceiver { public static boolean wasScreenOn = true; @Override public void onReceive(final Context context, final 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; } } } 

活动

 public class ExampleActivity extends Activity { private BroadcastReceiver mReceiver = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // initialize receiver final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); 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 Log.e("MYAPP", "SCREEN TURNED OFF"); } else { // this is when onPause() is called when the screen state has not changed } super.onPause(); } @Override protected void onResume() { super.onResume(); // only when screen turns on if (!ScreenReceiver.wasScreenOn) { // this is when onResume() is called due to a screen state change Log.e("MYAPP", "SCREEN TURNED ON"); } else { // this is when onResume() is called when the screen state has not changed } } @Override protected void onDestroy() { if (mReceiver != null) { unregisterReceiver(mReceiver); mReceiver = null; } super.onDestroy(); } } 

你可以通过听Service这些事件来解决你的问题。