1

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

4

1 回答 1

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,已被弃用。

于 2016-05-05T03:40:27.137 回答