android - 使用 TargetApi 注释无法从较新的 API 中找到方法

标签 android eclipse

我想使用下一个代码为 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()。您的选择是:

  1. 放弃对 Android 1.x 的支持,或者

  2. 不要使用apply(),而是始终在您自己的后台线程中使用commit(),或者

  3. 使用静态 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/

相关文章:

java - MapReduce中的分割方法

android - 需要 Tensorflow 建议

android - ProGuard 明显跑不起来

java - 在 Microsoft Windows Mobile 6.5.3 Professional 上开发 java 应用程序

java - 此环境中未提供编译器。当执行 mvn clean package

java - 我如何在eclipse上检查gradle插件的版本

android - 由 SwipeRefreshLayout 触发时在 RecyclerView 中执行 LayoutAnimation 时出现问题

java - Android - 有关系统 UI 的问题

java - 客户端(Java)未连接到服务器(Kotlin)Android Studio,出了什么问题?

java - 如何访问 eclipse VM 参数中指定的属性?