今天希望应用程序的服务运行时,可以监听到屏幕的唤醒。继续百度学习法,连同监听闭幕关闭也一同学习了。
此种情况需要动态注册系统广播。在AndroidManifest.xml中静态注册的实际运行中无效。
private ScreenStatusReceiver mScreenStatusReceiver;
在需要的地方调用如下函数:
private void registSreenStatusReceiver() {
mScreenStatusReceiver = new ScreenStatusReceiver();
IntentFilter screenStatusIF = new IntentFilter();
screenStatusIF.addAction(Intent.ACTION_SCREEN_ON);
screenStatusIF.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(mScreenStatusReceiver, screenStatusIF);
}
使用结束后,注销:
unregisterReceiver(mScreenStatusReceiver);
ScreenStatusReceiver类:
class ScreenStatusReceiver extends BroadcastReceiver {
String SCREEN_ON = "android.intent.action.SCREEN_ON";
String SCREEN_OFF = "android.intent.action.SCREEN_OFF"; @Override
public void onReceive(Context context, Intent intent) {
if (SCREEN_ON.equals(intent.getAction())) {
Log.w("ppp","ppp-屏幕亮了");
}
else if (SCREEN_OFF.equals(intent.getAction())) {
Log.w("ppp","ppp-屏幕暗了");
}
}
}