Android pre-M版本下如何自动检测锁屏变更或清除?
Great question—this is a super common pain point when working with pre-Marshmallow Android Keystore, especially when relying on setEncryptionRequired() to keep keys encrypted at rest. Let’s break down reliable ways to detect lock screen changes or removal on Android <6.0:
1. 监听锁屏密码相关系统广播
Android 4.2 (API 17) and above provide system broadcasts that signal lock screen security changes. These are the most direct way to catch events as they happen:
Intent.ACTION_PASSWORD_CHANGED: Triggered when the user updates their lock PIN, pattern, or password.Intent.ACTION_PASSWORD_REMOVED: Triggered when the user disables all lock screen security.
Example Broadcast Receiver
Create a receiver to handle these events and validate your Keystore keys immediately:
public class LockScreenChangeReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (Intent.ACTION_PASSWORD_CHANGED.equals(action)) { handleLockSecurityUpdated(context); } else if (Intent.ACTION_PASSWORD_REMOVED.equals(action)) { handleLockSecurityCleared(context); } } private void handleLockSecurityUpdated(Context context) { // Check if your existing Keystore key is still accessible try { KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null); SecretKey storedKey = (SecretKey) keyStore.getKey("your_key_alias", null); if (storedKey == null) { // Key was deleted due to lock change—regenerate and re-encrypt data regenerateKeyAndReencryptData(context); } } catch (Exception e) { // Any error means the key is invalid—fall back to regeneration regenerateKeyAndReencryptData(context); } } private void handleLockSecurityCleared(Context context) { // Lock screen was removed—prompt user to re-enable security first Intent securitySettingsIntent = new Intent(Settings.ACTION_SECURITY_SETTINGS); context.startActivity(securitySettingsIntent); // After user sets new lock, regenerate keys and re-encrypt data } private void regenerateKeyAndReencryptData(Context context) { // Implement your logic to: // 1. Decrypt existing data with any fallback method (if possible) // 2. Generate a new Keystore key with setEncryptionRequired() // 3. Re-encrypt and re-store your data } }
Register the Receiver
Dynamic registration is more reliable than static (some custom ROMs restrict static broadcasts):
// In your Activity/Service onCreate() LockScreenChangeReceiver receiver = new LockScreenChangeReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_PASSWORD_CHANGED); filter.addAction(Intent.ACTION_PASSWORD_REMOVED); registerReceiver(receiver, filter); // Don't forget to unregister in onDestroy() @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(receiver); }
2. 定期验证Keystore密钥可用性
Broadcasts aren’t 100% reliable across all custom Android skins. Add a periodic check (e.g., on app launch, or in a background task) to confirm your key still works:
public boolean isKeystoreKeyValid(String keyAlias) { try { KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null); SecretKey key = (SecretKey) keyStore.getKey(keyAlias, null); if (key == null) return false; // Test if the key can actually perform encryption Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); cipher.doFinal("test_validation_data".getBytes()); return true; } catch (Exception e) { // Any exception (key not found, invalid state) means the key is dead return false; } }
If this method returns false, trigger your key regeneration and data re-encryption flow.
Critical Notes
- Custom ROM Limitations: Some manufacturers modify broadcast behavior, so never rely on broadcasts alone—always pair with periodic validation.
- Data Safety: Before lock screen changes, consider adding a backup mechanism for critical data (if compliance allows) to avoid permanent loss.
- User Guidance: When lock security is cleared, explicitly prompt users to re-enable it—you can’t create
setEncryptionRequired()keys without a secure lock screen.
内容的提问来源于stack exchange,提问作者Thinh Nguyen Van

