仿写Android屏幕解锁小应用


近日需要设置密码并加密,因此仿写了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);
        }
    }

进行保存。

  • 1
  • 2
  • 下一页

相关内容