`
Teok
  • 浏览: 150742 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Source share: SharedPreferencesCompat.java

阅读更多
Firstly look at the code:
/**
 * Reflection utils to call SharedPreferences$Editor.apply when possible,
 * falling back to commit when apply isn't available.
 */
public class SharedPreferencesCompat {
    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);
                return;
            } catch (InvocationTargetException unused) {
                // fall through
            } catch (IllegalAccessException unused) {
                // fall through
            }
        }
        editor.commit();
    }
}



这是google I/O 2010演讲Writing zippy Android apps演示项目里的一段代码,作者Brad Fitzpatrick
背景:
起先,Android的Editor只有commit一个提交方法:
/**
         * Commit your preferences changes back from this Editor to the
         * {@link SharedPreferences} object it is editing.  This atomically
         * performs the requested modifications, replacing whatever is currently
         * in the SharedPreferences.
         *
         * <p>Note that when two editors are modifying preferences at the same
         * time, the last one to call commit wins.
         *
         * <p>If you don't care about the return value and you're
         * using this from your application's main thread, consider
         * using {@link #apply} instead.
         *
         * @return Returns true if the new values were successfully written
         * to persistent storage.
         */
        boolean commit();

后来呢,应该是在开发Gingerbread的时候,这帮googlers折腾了一堆优化性能的方法,然后就出来一个appy接口:
/**
         * Commit your preferences changes back from this Editor to the
         * {@link SharedPreferences} object it is editing.  This atomically
         * performs the requested modifications, replacing whatever is currently
         * in the SharedPreferences.
         *
         * <p>Note that when two editors are modifying preferences at the same
         * time, the last one to call apply wins.
         *
         * <p>Unlike {@link #commit}, which writes its preferences out
         * to persistent storage synchronously, {@link #apply}
         * commits its changes to the in-memory
         * {@link SharedPreferences} immediately but starts an
         * asynchronous commit to disk and you won't be notified of
         * any failures.  If another editor on this
         * {@link SharedPreferences} does a regular {@link #commit}
         * while a {@link #apply} is still outstanding, the
         * {@link #commit} will block until all async commits are
         * completed as well as the commit itself.
         *
         * <p>As {@link SharedPreferences} instances are singletons within
         * a process, it's safe to replace any instance of {@link #commit} with
         * {@link #apply} if you were already ignoring the return value.
         *
         * <p>You don't need to worry about Android component
         * lifecycles and their interaction with <code>apply()</code>
         * writing to disk.  The framework makes sure in-flight disk
         * writes from <code>apply()</code> complete before switching
         * states.
         *
         * <p class='note'>The SharedPreferences.Editor interface
         * isn't expected to be implemented directly.  However, if you
         * previously did implement it and are now getting errors
         * about missing <code>apply()</code>, you can simply call
         * {@link #commit} from <code>apply()</code>.
         */
        void apply();


看完这两个方法的说明,你大概就明白了是神马意思了吧。反正是apply在某种程度上降低了main thread的负担,但还能保证数据修改的很及时。(注意这部分:You don't need to worry about Android component lifecycles and their interaction with apply() writing to disk.  The framework makes sure in-flight disk writes from)

因此,出现这个SharedPreferencesCompat来兼容一下这两个api(compat就是compatible的缩写呀)。

ps:嗯。gingerbread为虾米快呢,这下有点了解了吧。。
0
7
分享到:
评论

相关推荐

    hive-jdbc-1.1.0-cdh5.4.5-standalone.jar

    at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Unknown Source) at ...

    webservice启动没有问题,通过自动生成的客户端报错

    faultString: java.lang.reflect.InvocationTargetException faultActor: faultNode: faultDetail: {http://xml.apache.org/axis/}stackTrace: AxisFault faultCode: {...

    maven3.6.3资源包

    1) Error injecting constructor, java.lang.NoSuchMethodError: org.apache.maven.model.validation.DefaultModelValidator: method 'void ()' not found at org.jetbrains.idea.maven.server.embedder....

    apple越狱备份数据

    at java.lang.Thread.run(Unknown Source) Caused by: java.lang.NullPointerException at com.semaphore.jna.LibraryFinder.loadPath(LibraryFinder.java:64) at com.semaphore.jna.LibraryFinder.&lt;clinit&gt;...

    【解决方案】pyspark 初次连接mongo 时报错Class not found exception:com.mongodb.spark.sql.DefaultSource

     df = spark.read.format(com.mongodb.spark.sql.DefaultSource).load()  File /home/cisco/spark-2.2.0-bin-hadoop2.7/python/lib/pyspark.zip/pyspark/sql/readwriter.py, line 165, in load  

    hive-jdbc-2.1.0-standalone.jar

    at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Unknown Source) at ...

    Easy.JAVA.to.Source.Converte

    【标题】:Easy.JAVA.to.Source.Converte 是一个专门用于将已编译的Java字节码文件(.class)转换回源代码(.java)的工具。这个软件可以帮助开发者在丢失或忘记源代码的情况下,从已有的.class文件中恢复部分或全部...

    1.zipSource Server : changgou Source Server Type : MySQL Source Ser

    Source Server : changgou Source Server Type : MySQL Source Server Version : 50726 Source Host : 192.168.159.134:3306 Source Schema : changgou_all Target Server Type : MySQL Target Server ...

    jaxen.jar和dom4j.jar

    at java.lang.reflect.Method.invoke(Unknown Source) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44) at org.junit.internal.runners.model.ReflectiveCallable.run...

    bcprov加密库

    org.bouncycastle.openssl.PEMException: problem parsing ENCRYPTED PRIVATE KEY: java.lang.SecurityException: JCE cannot authenticate the provider BC at org.bouncycastle.openssl.PEMReader$...

    aa.rar_https://aa_one more_tube47aa_‘www.aatube.cn

    Tube ...Traducir esta página Top comments Newest first. mark kenneth santos 2 years ago. nice one brod sis :) viva viva magicfive longlive ,,,,, proud to be a dsffcs.....Tripoud ...Traducir esta página ...

    优雅的操作文件:java.nio.file 库介绍.pdf

    Path source = Paths.get("source.txt"); Path target = Paths.get("target.txt"); // 创建文件 Files.createFile(source); // 检查文件是否存在 if (Files.exists(source)) { System.out.println("Source ...

    jdbc--sqljdbc4-2.0.jar

    at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.load...

    castor-1.0-xml.jar

    org.exolab.javasource.JEnum org.exolab.javasource.JType org.exolab.castor.util.List org.exolab.javasource.Header org.exolab.javasource.JClass org.exolab.javasource.JField org.exolab.castor.types.Date ...

    今天在windows7下安装qt-opensource-windows-x86-5.12.9报错: gdb.exe -系统错误

    今天在windows7下安装qt-opensource-windows-x86-5.12.9报错: gdb.exe -系统错误 无法启动此程序,因为计算机中丢失api-ms-win-core-path-l1-1-0.dll。尝试重新安装该程序以解决此问题

    java调用net开发的webservice实例

    javax.wsdl.WSDLException: WSDLException: faultCode=PARSER_ERROR: Problem parsing '- WSDL Document -'.: org.xml.sax.SAXParseException: The element type "p" must be terminated by the matching end-tag ...

    ES6版地图瓦片颜色工具:tileSourceColor.js

    openlayers 加载蓝黑色天地图颜色工具类,openlayers 加载蓝黑色底图。 使用介绍: 直接 import 然后使用 TileSourceColor.getSource (图层对象,类型) 即可。... source: TileSourceColor.getSource(layer, type) });

    java源码生成器-platform.javasource:Java源代码生成器

    java原始生成器#platform.javasource ## Java源代码生成器 该库允许您以“功能”样式从Java代码生成Java源代码。 只需将代码创建为模型并将其打印到打印流中 示例:创建Web servlet源代码 String pname = "my...

    javashop_source_2.1.3.part1.rar

    javashop_source_2.1.3.part1.rar JAVASHOP源码(内带jar包) 由于只能上传小于20MB的文件,所以压缩成两个文件上传,只要把这两个压缩包都下载后,然后选中两个包一起解压即可。。 javashop_source_2.1.3.part2....

    jface开发的几个包都在里面了

    at java.lang.Class.privateGetDeclaredMethods(Unknown Source) at java.lang.Class.getMethod0(Unknown Source) at java.lang.Class.getMethod(Unknown Source) at sun.launcher.LauncherHelper.getMainMethod...

Global site tag (gtag.js) - Google Analytics