Skip to content

Instantly share code, notes, and snippets.

@adityabhaskar
Created November 27, 2021 16:23
Show Gist options
  • Save adityabhaskar/6ebbd4ec29b9fa8cb8edacf6939e4570 to your computer and use it in GitHub Desktop.
Save adityabhaskar/6ebbd4ec29b9fa8cb8edacf6939e4570 to your computer and use it in GitHub Desktop.
Access SharedPreferences without StrictMode warnings
private fun <T> withPrefs(context: Context, callback: SharedPreferences.() -> T): T {
val oldPolicy = StrictMode.allowThreadDiskWrites()
val output = context.applicationContext
.getSharedPreferences(BILLING_STORAGE_NAME, Context.MODE_PRIVATE)
.callback()
StrictMode.setThreadPolicy(oldPolicy)
return output
}
// Sample
fun getThatBool(context: Context, key: String): Boolean {
return withPrefs(context) { getBoolean(key, false) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment