在做解锁监听程序时,一开始采用监听屏幕SCREEN_ON和SCREEN_OFF这两个action。
但奇怪的是,这两个action只能通过代码动态的形式注册,才能被监听到,使用AndroidManifest.xml 完全监听不到。
百度后发现这是PowerManager那边在发这个广播的时候做了限制,限制只能有register到代码中的receiver才能接收。
后来就找各种能静态注册AndroidManifest.xml同时能反映用户解锁行为的广播.于是找到android.intent.action.USER_PRESENT.
每个用户隔一段时间重新开始使用手机时,首先按电源键点亮屏幕,紧接着解锁。android.intent.action.USER_PRESENT就是解锁时发出的intent.
于是,监听android.intent.action.USER_PRESENT就能识别用户进入home界面,进而启动想启动的相关服务,包括弹出对话框welcome用户\后台启动程序升级服务等等。
来个动态监听解锁屏类
public class ScreenObserver {
private static String TAG = "ScreenObserver";
private Context mContext;
private ScreenBroadcastReceiver mScreenReceiver;
private ScreenStateListener mScreenStateListener;
private static Method mReflectScreenState;
public ScreenObserver(Context context) {
mContext = context;
mScreenReceiver = new ScreenBroadcastReceiver();
try {
mReflectScreenState = PowerManager.class.getMethod("isScreenOn",
String.class);
} catch (NoSuchMethodException nsme) {
Log.d(TAG, "API < 7," + nsme);
}
}
/**
* screen状态广播接收者
*
* @author zhangyg
*/
private class ScreenBroadcastReceiver extends BroadcastReceiver {
private String action = null;
@Override
public void onReceive(Context context, Intent intent) {
action = intent.getAction();
if (Intent.ACTION_SCREEN_ON.equals(action)) {
mScreenStateListener.onScreenOn();
} else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
mScreenStateListener.onScreenOff();
}
}
}
/**
* 请求screen状态更新
*
* @param listener
*/
public void requestScreenStateUpdate(ScreenStateListener listener) {
mScreenStateListener = listener;
startScreenBroadcastReceiver();
firstGetScreenState();
}
/**
* 第一次请求screen状态
*/
private void firstGetScreenState() {
PowerManager manager = (PowerManager) mContext
.getSystemService(Activity.POWER_SERVICE);
if (isScreenOn(manager)) {
if (mScreenStateListener != null) {
mScreenStateListener.onScreenOn();
}
} else {
if (mScreenStateListener != null) {
mScreenStateListener.onScreenOff();
}
}
}
/**
* 停止screen状态更新
*/
public void stopScreenStateUpdate() {
mContext.unregisterReceiver(mScreenReceiver);
}
/**
* 启动screen状态广播接收器
*/
private void startScreenBroadcastReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
mContext.registerReceiver(mScreenReceiver, filter);
}
/**
* screen是否打开状态
*
* @param pm
* @return
*/
private static boolean isScreenOn(PowerManager pm) {
boolean screenState;
try {
screenState = (Boolean) mReflectScreenState.invoke(pm);
} catch (Exception e) {
screenState = false;
}
return screenState;
}
public interface ScreenStateListener {
public void onScreenOn();
public void onScreenOff();
}
}