Use screen lock in my app

2020-05-25 11:07发布

Is it possible to use the default security settings, which user has set to the phone, as a locking or login mechanism for my app too? I mean like when we reset the phone, it asks for phone password or pattern.

Is it possible the same way that I can use the default android password or pattern set by user to login to my app?

My goal is to bypass the developing effort and use some standard way of authentication without making user to remember another new password.

NOTE: I'm aware that I can lock the screen programmatically. But instead, I want to use the lock as a verification before performing any critical operation. (Just like how Settings ask for the password before resetting the the phone.)

2条回答
劫难
2楼-- · 2020-05-25 11:22

I'm just following @agi with few enhancement,

    public class MainActivity extends AppCompatActivity {
    private static int CODE_AUTHENTICATION_VERIFICATION=241;

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

        KeyguardManager km = (KeyguardManager)getSystemService(KEYGUARD_SERVICE);
        if(km.isKeyguardSecure()) {

            Intent i = km.createConfirmDeviceCredentialIntent("Authentication required", "password");
            startActivityForResult(i, CODE_AUTHENTICATION_VERIFICATION);
        }
        else
            Toast.makeText(this, "No any security setup done by user(pattern or password or pin or fingerprint", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK && requestCode==CODE_AUTHENTICATION_VERIFICATION)
        {
            Toast.makeText(this, "Success: Verified user's identity", Toast.LENGTH_SHORT).show();
        }
        else
        {
            Toast.makeText(this, "Failure: Unable to verify user's identity", Toast.LENGTH_SHORT).show();
        }
    }
}
查看更多
可以哭但决不认输i
3楼-- · 2020-05-25 11:23

Actually, there is an API to exactly that using the KeyguardManager.

First get a the Keyguard SystemService:

KeyguardManager km = (KeyguardManager)getSystemService(KEYGUARD_SERVICE);

And then request an authentication intent using:

Intent i = km.createConfirmDeviceCredentialIntent(title,description);

start this intent using startActivityForResult(Intent, int) and check for RESULT_OK if the user successfully completes the challenge.

This is for API level 21. Previous versions might work with KeyguardLock.

查看更多
登录 后发表回答