There is a feature in Android called KeyGuard. Keyguard essentially refers to the code that controls phone unlocking. It was originally created for phones with keypads.
To protect the app, Tez, Paytm, etc. employ Android's Keyguard API.
You can implement this by following the steps:
-
Android provides KeyguardManager to implement authentication.
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
-
Create an intent to request for authentication.
Intent screenLockIntent = keyguardManager.createConfirmDeviceCredentialIntent(title, description);
Here, Title and description are for displaying to user the information while authenticating. API level 21 is required for this method.
-
You can call startActivityForResult which will return a result whether the authentication is successful.
startActivityForResult(screenLockIntent, LOCK_REQUEST_CODE);
This throws an exception if lock screen is not set up. You have to handle the situation manually.
-
Check the result in onActivityResult
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(LOCK_REQUEST_CODE == requestCode){
if (resultCode == RESULT_OK) {
//Authentication is successful
} else {
//Authentication failed
}
}
}