在 Android 6.0 项目中,我正在尝试使用接近传感器解锁手机。
这是我为 OnSensorChanged 事件所拥有的:
public void onSensorChanged(SensorEvent event) {
proxValue = (event.values[0]); //sensor value stored in proxValue
keyguardManager = (KeyguardManager)getSystemService(Activity.KEYGUARD_SERVICE);
lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
screenLock = ((PowerManager)getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
/*when service is running and phone is locked
and proximity sensor value is less than 2.0 centimeters*/
if(isMyServiceRunning(StartStopService.class) && lockStatus == true && proxValue < 2){
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(500); // vibrate for 500 ms
screenLock.acquire(); //to wake the phone up
lock.disableKeyguard(); //to unlock the phone
keyguardDisabled = true; // boolean to check keyguard status
}
}
在我的 ScreenReceiver 上,我有:
public class ScreenReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
keyguardManager = (KeyguardManager)getSystemService(Activity.KEYGUARD_SERVICE);
lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
screenLock = ((PowerManager)getSystemService(POWER_SERVICE)).newWakeLock(
PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
if((intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) || !(intent.getAction().equals(Intent.ACTION_USER_PRESENT)))
{
lockStatus = true;
if(keyguardDisabled){
lock.reenableKeyguard();
screenLock.release();
keyguardDisabled = false;
}
}
else
{
lockStatus = false;
}
}
}
当我调用 lock.disableKeyguard() 时会出现问题。它成功解锁并唤醒手机,但当我按下主页按钮时手机死机。我知道我需要在某个时候重新启用键盘保护,但是在哪里?什么可能是解决方案,或者有没有其他方法可以以编程方式解锁手机?