【移动开发】SharedPreferences的兼容版本

public class SharedPreferencesCompat {
    private static final String TAG = SharedPreferencesCompat.class
            .getCanonicalName();
    private static final Method sApplyMethod = findApplyMethod();

    private static Method findApplyMethod() {
        try {
            Class<?> cls = SharedPreferences.Editor.class;
            return cls.getMethod("apply");
        } catch (NoSuchMethodException unused) {
// fall through
        }
        return null;
    }

    public static void apply(SharedPreferences.Editor editor) {
        if (sApplyMethod != null) {
            try {
                sApplyMethod.invoke(editor);
                Log.d(TAG, "Apply method was invoked!");
                return;
            } catch (InvocationTargetException unused) {
// fall through
            } catch (IllegalAccessException unused) {
// fall through
            }
        }
        editor.commit();
        Log.d(TAG, "Commit method was invoked!");
    }
}


原文地址:https://www.cnblogs.com/xiaomaohai/p/6158014.html