android屏幕加解锁事件广播的监听


        想在程序中监听屏幕SCREEN_ON和SCREEN_OFF这两个action,实现屏幕锁定状态的监听,从而实现自己的相应功能。比较奇怪的是这两个action只能通过代码的形式注册才能被监听到,在AndroidManifest.xml中注册根本监听不到。去网上查了一下,原来是PowerManager那边在发这个广播的时候做了限制,限制只有register到代码中的receiver才能接收。特此记录!

 

 

 

public class ScreenActionReceiver extends BroadcastReceiver {

	private String TAG = "ScreenActionReceiver";
	private boolean isRegisterReceiver = false;

	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		if (action.equals(Intent.ACTION_SCREEN_ON)) {
			Logcat.d(TAG, "屏幕解锁广播...");
		} else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
			Logcat.d(TAG, "屏幕加锁广播...");
		}
	}

	public void registerScreenActionReceiver(Context mContext) {
		if (!isRegisterReceiver) {
			isRegisterReceiver = true;

			IntentFilter filter = new IntentFilter();
			filter.addAction(Intent.ACTION_SCREEN_OFF);
			filter.addAction(Intent.ACTION_SCREEN_ON);
			Logcat.d(TAG, "注册屏幕解锁、加锁广播接收者...");
			mContext.registerReceiver(ScreenActionReceiver.this, filter);
		}
	}

	public void unRegisterScreenActionReceiver(Context mContext) {
		if (isRegisterReceiver) {
			isRegisterReceiver = false;
			Logcat.d(TAG, "注销屏幕解锁、加锁广播接收者...");
			mContext.unregisterReceiver(ScreenActionReceiver.this);
		}
	}

}


你可能感兴趣的:(Android开发)