Android Keyguard 呼叫螢幕解鎖驗證

android 的 Keyguard 可以用來呼叫螢幕解鎖來驗證,運用在有做自動登入時,避免使用者手機被偷,可以在app的重要功能再次要求解鎖



先檢查手機是否有開啟螢幕鎖定。 在Activity 叫起驗證頁,可以客制Title、Description
private void showAuthenticationScreen() {
   if (keyguardManager.isKeyguardSecure()) {
       // Custom title description
       Intent intent = keyguardManager.createConfirmDeviceCredentialIntent("This is a custom title", "This is a custom description");
       if (intent != null) {
           startActivityForResult(intent, REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS);
       }else{
            this.result.setText("Secure lock screen hasn't set up");
       }
   }else{
       this.result.setText("Secure lock screen hasn't set up");
   }
}
接收解鎖結果:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS) {
       if (resultCode == RESULT_OK) {
           this.result.setText("Success");
       } else {
            this.result.setText("Cancel");
       }
    }
}
完整程式:
public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS = 1;
    private KeyguardManager keyguardManager;
    private TextView result;

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

        this.result = (TextView)findViewById(R.id.result);
        keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
    }

    private void showAuthenticationScreen() {
        if (keyguardManager.isKeyguardSecure()) {
            // Custom title description
            Intent intent = keyguardManager.createConfirmDeviceCredentialIntent("This is a custom title", "This is a custom description");
            if (intent != null) {
                startActivityForResult(intent, REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS);
            }else{
                this.result.setText("Secure lock screen hasn't set up");
            }
        }else{
            this.result.setText("Secure lock screen hasn't set up");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS) {
            if (resultCode == RESULT_OK) {
                this.result.setText("Success");
            } else {
                this.result.setText("Cancel");
            }
        }
    }

    public void verify(View view){
        this.showAuthenticationScreen();
    }
}

public boolean isDeviceLocked()

返回設備當前是否已鎖定並需要PIN,模式或密碼才能解鎖。

public boolean isKeyguardSecure()

返回設備是否使用PIN,模式或密碼進行保護。

留言

這個網誌中的熱門文章

Android - 使用 adb 安装apk

Android TextView autosizing 自動調整大小

Kotlin - 實現Android中的Parcelable