歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 仿寫Android屏幕解鎖小應用

仿寫Android屏幕解鎖小應用

日期:2017/3/1 10:46:02   编辑:Linux編程

近日需要設置密碼並加密,因此仿寫了Android的位置和安全設置有更改屏幕鎖定的設置。先看效果圖:

點擊後,第一次是可設置密碼。

設置成功密碼後再點Button按鈕將會出現:


由於時間緊,因此只研究了字母和數字設置的密碼。


思路分析如下:

將密碼加密後放置到一個文件裡,如果讀了來為空則認為沒有設置密碼,這樣,你需要先設置密碼,若不為空,則是要確認密碼。因此需要一個設置密碼的類ChooseMasterLockPassword,一個確認密碼的類ConfirmMasterLockPassword,還有一個幫助類ChooseMasterLockSettingsHelper,和一個工具類LockPatternUtils(Android原來將這個類是放置在/frameworks/base/core/java/com/android/internal/widget下,我對它進行了改寫,因為它原來是將數據保存到/data/system下面,權限不夠的話就沒法訪問,並且這個類主要是為屏幕鎖定服務,因此需要改寫一下)。另外還有一個選擇加密方式的類ChooseMasterLockGeneric,即選擇密碼為無還是pin加密或是密碼加密。

主要代碼如下:

[1] 先由Button點擊進入到ChooseMasterLockGeneric:

ChooseMasterLockSettingsHelper helper = new ChooseMasterLockSettingsHelper(this);
helper.launchConfirmationActivity(CONFIRM_EXISTING_REQUEST, null, null)) 來判斷是否存在密碼。

[2] 再在onPreferenceTreeClick中傳入參數寫入點擊的響應代碼:

updateUnlockMethodAndFinish(DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);

如:清空密碼:mChooseLockSettingsHelper.utils().clearMasterLock_KP();

設置密碼:

Intent intent = new Intent().setClass(this, ChooseMasterLockPassword.class);
intent.putExtra(LockPatternUtils.PASSWORD_TYPE_KEY, quality);
intent.putExtra(ChooseMasterLockPassword.PASSWORD_MIN_KEY, minLength);
intent.putExtra(ChooseMasterLockPassword.PASSWORD_MAX_KEY, maxLength);
intent.putExtra(CONFIRM_CREDENTIALS, false);
intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
startActivity(intent);

啟動到ChooseMasterLockPassword

[3] 如何保存密碼:

String dataSystemDirectory = "/data/data/com.android.lock/";
// Added by Hao Jingjing at 2011-12-21
sLockMasterPasswordFilename_KP = dataSystemDirectory + LOCK_MASTERPASSWORD_FILE_KP;

通過:

public void saveMasterLockPassword_KP(String password) {
// Compute the hash
final byte[] hash = passwordToHash(password);
try {
// Write the hash to file
RandomAccessFile raf = new RandomAccessFile(sLockMasterPasswordFilename_KP, "rw");
// Truncate the file if pattern is null, to clear the lock
if (password == null) {
raf.setLength(0);
} else {
raf.write(hash, 0, hash.length);
}
raf.close();
} catch (FileNotFoundException fnfe) {
// Cant do much, unless we want to fail over to using the settings provider
Log.e(TAG, "Unable to save lock pattern to " + sLockMasterPasswordFilename_KP);
} catch (IOException ioe) {
// Cant do much
Log.e(TAG, "Unable to save lock pattern to " + sLockMasterPasswordFilename_KP);
}
}

進行保存。

Copyright © Linux教程網 All Rights Reserved