应用程序上的disableKeyguard呼叫冻结电话

时间:2016-04-24 22:51:40

标签: android android-sensors keyguard

在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()时会出现问题。它成功解锁并唤醒手机,但是当我按下主页按钮时手机会冻结。我知道我需要在某个时刻重新启用键盘锁,但在哪里?可能是什么解决方案,还是有其他方式以编程方式解锁手机?

1 个答案:

答案 0 :(得分:0)

如果有人遇到同样的问题,我通过创建一个活动来解决它,并在onCreate方法中添加:

//StartStopActivity
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | 
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | 
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | 
WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);

在我的服务上,我开始了这样的活动:

//StartStopService
Intent dialogIntent = new Intent(this, StartStopActivity.class);
                dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(dialogIntent);

旧方法不适用于Marshmallow,不推荐使用。