Could not re-enable the KeyGaurd once disabled it

妖精的绣舞 提交于 2019-12-24 01:06:57

问题


I have write below code to toggle the KeyGaurd of my android phone using a toggle button. but I am facing an strange behavior.

  • it disables the keygaurd successfully but. not re-enabling.

     btnToggleLock.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
    
            if (btnToggleLock.isChecked()) {
    
                toast.cancel();
                toast.setText("Unlocked");
                toast.show();
    
                Log.i("Unlocked", "If");
    
                KeyguardManager myKeyGuard = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
    
                KeyguardLock myLock = myKeyGuard
                        .newKeyguardLock(KEYGUARD_SERVICE);
                myLock.disableKeyguard();
    
    
            } else {
    
                toast.cancel();
                toast.setText("Locked");
                toast.show();
    
                KeyguardManager myKeyGuard = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
                KeyguardLock myLock = myKeyGuard
                        .newKeyguardLock(KEYGUARD_SERVICE);
                myLock.reenableKeyguard();
    
                Log.i("Locked", "else");
    
            }
    
        }
    });
    
  • it disables the keygaurd successfully but. not re-enabling.

  • I tested it the control is traversing both if and as well as else

also I m using android 2.2.1 motoralla milestone.


回答1:


The issue here is that you are creating a new Lock (KeyGuardLock) every time the "if" statement executes. You can disable a lock the first time when you create it but you must "reenable" the lock which you disabled in the first place, you cannot create a new one.

The solution is to make the lock outside of the onClickListener. i.e. Take the following code out of the "if" statement and declare it before setting the onClickListener:-

KeyguardManager myKeyGuard = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
            KeyguardLock myLock = myKeyGuard
                    .newKeyguardLock(KEYGUARD_SERVICE);


来源:https://stackoverflow.com/questions/15338400/could-not-re-enable-the-keygaurd-once-disabled-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!