PreferenceManager getDefaultSharedPreferences deprecated in Android Q

你说的曾经没有我的故事 提交于 2020-07-16 16:18:48

问题


PreferenceManager getDefaultSharedPreferences is deprecated in Android Q, how do I replace it?


回答1:


You can use AndroidX support library version of PreferenceManager, i.e. androidx.preference.PreferenceManager and not android.preference.PreferenceManager.

remember to add the following to your build.gradle.

implementation 'androidx.preference:preference:1.1.1'



回答2:


Package preference provides the androidx PreferenceManager:

Java: implementation "androidx.preference:preference:1.1.1"

Kotlin: implementation "androidx.preference:preference-ktx:1.1.1"


i.e. change android.preference.PreferenceManager to androidx.preference.PreferenceManager


Also see PreferenceFragmentCompat, which is the current PreferenceFragment class to use.




回答3:


Quote from PreferenceManager documentation:

This class was deprecated in API level 29.
Use the AndroidX Preference Library for consistent behavior across all devices. For more information on using the AndroidX Preference Library see Settings.




回答4:


Yes, it is deprecated. Use the AndroidX Preference Library for consistent behavior across all devices. For more information on using the AndroidX Preference Library see Settings.

Follow this -

PreferenceManager




回答5:


If you're just saving and retrieving key-value pairs you can replace:

 prefs = PreferenceManager.getDefaultSharedPreferences(this); 

with:

 prefs = getSharedPreferences(
            "my.app.packagename_preferences", Context.MODE_PRIVATE);

Be sure to use the right file name for the new implementation or your users will lose access to everything saved with getDefaultSharedPreferences(!). The following will get the file name getDefaultSharedPreferences uses:

getPackageName() + "_preferences"


来源:https://stackoverflow.com/questions/56833657/preferencemanager-getdefaultsharedpreferences-deprecated-in-android-q

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!