我想使用下一个代码为 4 之后的所有 Android API 应用 SharedPreferences。
/**
* The apply method was introduced
* in Android API level 9.<br> Calling it causes a safe asynchronous write
* of the SharedPreferences.Editor object to be performed. Because
* it is asynchronous, it is the preferred technique for saving SharedPreferences.<br>
* So we should use appropriate method if we doesn`t need confirmation of success.
* In this case we should use old commit method.
*/
@TargetApi(9)
public static void applySharedPreferences(SharedPreferences.Editor editor){
if (Build.VERSION.SDK_INT < 9){
editor.commit();
} else {
editor.apply();
}
}
项目目标 API 为 10(在项目属性中设置)。 它在 API 8 上运行良好,但当我尝试在 API 4 上运行它时,它崩溃并显示下一条消息:
11-18 20:21:45.782: E/dalvikvm(323): Could not find method android.content.SharedPreferences$Editor.apply, referenced from method my.package.utils.Utils.applySharedPreferences
它正常安装在设备上,但在启动过程中崩溃。为什么在此 API 中从未使用过此方法(应用)时会发生这种情况?
谢谢
最佳答案
It works fine on API 8, but when I try to run it on API 4 it is crashed with the next message:
Android 1.x 中的 Dalvik 非常保守,如果您尝试加载包含它无法解析的引用的类,它会崩溃——在本例中为 apply()
。您的选择是:
放弃对 Android 1.x 的支持,或者
不要使用
apply()
,而是始终在您自己的后台线程中使用commit()
,或者使用静态
apply()
方法创建另一个类(例如,GingerbreadHelper
),该方法将您的SharedPreferences.Editor
作为参数并对其调用apply()
。然后,将applySharedPreferences()
更改为使用GingerbreadHelper.apply(editor)
而不是editor.apply()
。只要您从不在 Android 1.x 设备上加载GingerbreadHelper
,就可以避免VerifyError
。
关于android - 使用 TargetApi 注释无法从较新的 API 中找到方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13444255/