How to lock/unlock the screen with Pattern/Password mode in Android?
Asked Answered
R

1

13

I was successful to lock/unlock my screen using DevicePolicyManager and KeyguardManager in Android L. It worked well when I lock/unlock screen using swipe mode (no security). However, I cannot lock/unlock it when I lock/unlock screen by using Pattern and Password mode (higher security). Is it possible to lock/unlock screen with high security using DevicePolicyManager and KeyguardManager. ? This is what I did

protected static final int REQUEST_ENABLE = 0;
DevicePolicyManager devicePolicyManager;
ComponentName adminComponent;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button button = (Button) findViewById(R.id.btn);
    button.setOnClickListener(btnListener);

}

//LOCK
Button.OnClickListener btnListener = new Button.OnClickListener() {
    public void onClick(View v) {
        adminComponent = new ComponentName(MainActivity.this, Darclass.class);
        devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);

        if (!devicePolicyManager.isAdminActive(adminComponent)) {

            Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
            intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, adminComponent);
            startActivityForResult(intent, REQUEST_ENABLE);
        } else {
            devicePolicyManager.lockNow();
        }

    }
}; 

//UNLOCK
 private KeyguardManager keyguardManager;
 KeyguardManager.KeyguardLock kl;
 keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
 kl = keyguardManager.newKeyguardLock("MyKeyguardLock");
 kl.disableKeyguard();

Note that, I am using it in a service.

Rocco answered 25/9, 2016 at 10:5 Comment(0)
B
0

You mentioned that you are using the code in a Service, but while constructing your adminComponent ComponentName object you provide MainActivity.this as your context ! MainActivity.this might be NULL if your MainActivity is not currently running.

I suggest you initiate adminComponent with the Service class as the Context.

Billboard answered 13/10, 2016 at 12:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.