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

SIL*_*NIK 2 eclipse android

从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();
    }
}
Run Code Online (Sandbox Code Playgroud)

项目目标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
Run Code Online (Sandbox Code Playgroud)

它通常安装在设备上,但在启动时会崩溃.为什么在此API中没有使用此方法(apply)时会发生这种情况?

谢谢

Com*_*are 5

它在API 8上工作正常,但是当我尝试在API 4上运行它时,它会在下一条消息中崩溃:

Android 1.x中的Dalvik非常保守,如果你试图加载一个包含它无法解析的引用的类会崩溃 - 在这种情况下,apply().你的选择是:

  1. 删除对Android 1.x的支持,或

  2. 不要使用apply(),但只是总是commit()在你自己的后台线程中使用,或者

  3. GingerbreadHelper使用静态apply()方法创建另一个类(例如),该方法将您SharedPreferences.Editor作为参数并对其进行调用apply().然后,applySharedPreferences()改为使用GingerbreadHelper.apply(editor)而不是editor.apply().只要您从未加载GingerbreadHelperAndroid 1.x设备,就可以避免使用VerifyError.

  • @Chris.Jenkins:Android 2.0迎来了一个更友善,更温和的Dalvik,在加载课程时不会立即失败.它会等到你试图*使用它无法解析的引用,然后崩溃.这对基于Build`的版本保护块有很大帮助. (2认同)