MainActivity中
public class MainActivity extends Activity {
private WakeAndLockReceiver wakeAndLockReceiver;
@Override
protected void onCreate ( Bundle savedInstanceState) {
super . onCreate ( savedInstanceState) ;
setContentView ( R . layout. activity_main) ;
wakeAndLockReceiver = new WakeAndLockReceiver ( ) ;
IntentFilter intentFilter = new IntentFilter ( ) ;
intentFilter. addAction ( Intent . ACTION_SCREEN_ON ) ;
intentFilter. addAction ( Intent . ACTION_SCREEN_OFF ) ;
registerReceiver ( wakeAndLockReceiver, intentFilter) ;
}
class WakeAndLockReceiver extends BroadcastReceiver {
@Override
public void onReceive ( Context context, Intent intent) {
if ( intent == null ) return ;
String action = intent. getAction ( ) ;
if ( Intent . ACTION_SCREEN_ON . equals ( action) ) {
Log . d ( "wpz" , "onReceive: wake" ) ;
} else if ( Intent . ACTION_SCREEN_OFF . equals ( action) ) {
Log . d ( "wpz" , "onReceive: Lock" ) ;
} else {
return ;
}
}
}
@Override
protected void onDestroy ( ) {
super . onDestroy ( ) ;
unregisterReceiver ( wakeAndLockReceiver) ;
}
}
AndroidManifest.xml中
< uses-permission android: name= " android.permission.WAKE_LOCK" />
结果