Key-Valueペアの読み書きを行う時の候補です。
- SharedPreferences
- EncryptedSharedPreferences
- Preferences DataStore
目次
SharedPreferences
API level 1から存在するKey-Valueを保存する時のAPIです。
SharedPreferencesにはUIスレッドで安全に呼び出せないことがまれにあります。
参考
- https://qiita.com/ryo_mm2d/items/584e7ac12ced9a35b91f
- https://muumuutech.hatenablog.com/entry/2020/10/02/134452
EncryptedSharedPreferences
SharedPreferences
クラスをラップしたキーと値を自動的に暗号化するJetpackライブラリです。
キーは、暗号化された状態でも検索できるように、決定性暗号化アルゴリズムを使用して暗号化されます。
値は、AES-256 GCM を使用して暗号化されます。これは非決定性です。
ただしサポートされている端末の制限があり、現在(2022/5/1)安定版の1.0.0
ではAndroid 6.0(API レベル 23)以降を搭載した端末がサポートされています。
Preferences DataStore
Key-Valueペアや任意の型付きのオブジェクトを格納できるJetpackライブラリです。
DataStoreはKotlinコルーチンとフローを使用して、データを非同期的で扱うことができます。
SharedPreferencesとDataStoreの違い
出典:https://developer.android.com/codelabs/android-preferences-datastore#3
ファイル構造
-
SharedPreferences
-
EncryptedSharedPreferences
-
Preferences DataStore
SharedPreferencesの保存場所の確認方法はこちら
読み書きの仕方
-
SharedPreferences
val normalPreferences = context.getSharedPreferences(NORMAL_FILE_NAME, Context.MODE_PRIVATE) // Read normalPreferences.getString("normal-preferences-key", "Nothing") // Write normalPreferences .edit() .putString("normal-preferences-key", "normal-preferences-value") .apply()
-
EncryptedSharedPreferences
val encryptedPreferences = EncryptedSharedPreferences.create( ENCRYPTED_FILE_NAME, mainKeyAlias, context, EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM ) // Read encryptedPreferences.getString("encrypted-preferences-key", "Nothing") // Write encryptedPreferences .edit() .putString("encrypted-preferences-key", "encrypted-preferences-value") .apply()
-
Preferences DataStore
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings") val PREFERENCES_DATA_STORE_KEY = stringPreferencesKey("preferences-dataStore-key") // Read context.dataStore.data .catch { exception -> if (exception is IOException) { emit(emptyPreferences()) } else { throw exception } } .map { preferences -> preferences[PREFERENCES_DATA_STORE_KEY] ?: "" } // Write context.dataStore.edit { settings -> settings[PREFERENCES_DATA_STORE_KEY] = "preferences-dataStore-value" }
この記事へのコメントはありません。