使用系統內建ScreenLock來保護你的App,screenlockapp
如果你的App需要驗證密碼,我們可以使用系統的ScreenLock來進行驗證,這樣做的好處是我們的使用者不必使用多個不同的密碼來驗證身份,OK,下面我們來看看如何使用系統鎖屏:
先來介紹幾個Framework裡面的鎖屏相關的類:
LockPatternUtils:這裡提供了鎖屏的一些協助類,我們最需要使用的是這樣一個方法:
public boolean isSecure() { long mode = getKeyguardStoredPasswordQuality(); final boolean isPattern = mode == DevicePolicyManager.PASSWORD_QUALITY_SOMETHING; final boolean isPassword = mode == DevicePolicyManager.PASSWORD_QUALITY_NUMERIC || mode == DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC || mode == DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC || mode == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX; final boolean secure = isPattern && isLockPatternEnabled() && savedPatternExists() || isPassword && savedPasswordExists(); return secure; }
這個方法用來檢測當前系統是否已經使用了鎖屏。
ChooseLockGeneric:這個類是我們設定鎖屏的主要類:
我們通過調用這個類來引導使用者增加一個系統鎖屏:
Intent intent = new Intent("/"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); ComponentName cm = new ComponentName("com.android.settings","com.android.settings.ChooseLockGenericForKS"); intent.setComponent(cm); startActivity(intent);
那麼如何進行鎖屏的驗證呢,我們可以使用這樣一個方法:
private boolean runKeyguardConfirmation(int request) { Resources res = getActivity().getResources(); return new ChooseLockSettingsHelper(getActivity(), this) .launchConfirmationActivity(request, res.getText(R.string.master_clear_gesture_prompt), res.getText(R.string.master_clear_gesture_explanation)); }
我們需要在調用的Activity中使用onActivityResult來擷取傳回值:
if (requestCode == 55 && resultCode == Activity.RESULT_OK) {
55是我們的request code。
通過以上方法,我們就可以在我們的App中添加驗證、增加系統鎖屏驗證了。
以上。