2

我想使用下一个代码为自 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 中从未使用过此方法(应用)时会发生这种情况?

谢谢

4

2 回答 2

5

它在 API 8 上运行良好,但是当我尝试在 API 4 上运行它时,它会因下一条消息而崩溃:

在 Android 1.x 中,Dalvik 非常保守,如果您尝试加载包含无法解析的引用的类(在本例中为apply(). 您的选择是:

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

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

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

于 2012-11-18T20:58:27.850 回答
1

这不是走错路了吗?

那不应该是:

@TargetApi(9)
public static void applySharedPreferences(SharedPreferences.Editor editor)
{
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD)
    {
        editor.apply();
    }
    else
    {
        editor.commit();
    }
}

如果对你来说,那会解决的!

虽然更好!

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public static void applySharedPreferences(final SharedPreferences.Editor editor)
{
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD)
    {
        editor.apply();
    }
    else
    {
        new AsyncTask<Void, Void, Void>(){
            @Override
            protected Void doInBackground(Void... params)
            {
                editor.commit();
                return null;
            }
        }.execute();
    }
}

它现在总是异步的!

于 2012-11-18T20:33:48.830 回答