楽天アフィリエイト

2022年5月12日木曜日

PreferenceDataStore での起動判定

 Androidでの起動判定をDataStoreを使用して実施

忘備録としてプログラムの一部を記載


DataStoreが安定版の1.0.0

// Preferences DataStore
implementation 'androidx.datastore:datastore-preferences:1.0.0'
implementation 'androidx.datastore:datastore-preferences-core:1.0.0'


DataStoreSetting.kt


val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "DataStoreSetting")

class DataStoreSetting {
object PreferenceKey {
val START_FLAG = booleanPreferencesKey("StartFlag")
}

// 起動フラグの取得
suspend fun getFlag(context: Context): Boolean {

// DataStoreからフラグを取得
val flagFlow: Flow<Boolean> = context.dataStore.data
.catch { exception ->
if (exception is IOException) {
emit(emptyPreferences())
} else {
throw exception
}
}.map { preferences ->
// デフォルト値:false
preferences[PreferenceKey.START_FLAG] ?: false
}

// 起動フラグ取得
val flag = flagFlow.first()

return flag
}

// 起動フラグの設定
fun setFlag(context: Context) {
CoroutineScope(Dispatchers.Main).launch {
context.dataStore.edit { setting ->
setting[PreferenceKey.START_FLAG] = true
}
}
}

}


Fragment

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)

// 非同期処理
CoroutineScope(Dispatchers.Main).launch {

val intent: Intent
// 起動フラグ
val startFlag = dataStoreSetting.getSetupCompletedFlag(requireContext())

intent = if (startFlag) {
Intent(activity, SecondActivity::class.java)
} else {
Intent(activity, FirstActivity::class.java)
}
    }
    dataStoreSetting.setFlag(requireContext())
startActivity(intent)
}


参考サイト:

https://developer.android.com/topic/libraries/architecture/datastore?hl=ja

https://developer.android.com/codelabs/android-preferences-datastore?hl=ja#0

https://zenn.dev/slowhand/articles/455aa5cd244e90

https://akira-watson.com/android/sharedpreferences.html

https://stackoverflow.com/questions/67265984/is-it-possible-to-read-write-primitive-types-from-datastore-without-flows