【问题标题】:android which class provide definition to SharedPreferences interfaceandroid哪个类为SharedPreferences接口提供定义
【发布时间】:2016-03-18 20:25:06
【问题描述】:

如果查看SharedPreferences,它清楚地表明它是Android SDK 中的一个接口。

公共接口 SharedPreferences

谁能帮我更好地理解哪个类确切地为SharedPreferences的函数提供了定义?

【问题讨论】:

  • 问题是关于SharedPreferences 的实现,我知道它是接口但无法找到哪个类给它定义。

标签: android class interface sharedpreferences


【解决方案1】:

getSharedpreference()ContextWrapper 类的函数。并且ContextWrapper 类被Every Activity 类扩展。

当我们使用getSharedpreference() 方法时,它会被上下文类调用。它在上下文类对象中。但它返回 Sharedpreferences 对象。 共享首选项不是一个类,它是一个接口。 getSharedpreference() 是这个接口的唯一参考。

【讨论】:

    【解决方案2】:

    它是一个接口,在android的文档中没有错误。你也可以在SharedPreferences的源代码中看到:

    public interface SharedPreferences {
    

    挖掘android的源码,我们可以看到Activity扩展自ContextWrapper

    public class Activity extends ContextThemeWrapper
        implements LayoutInflater.Factory2,
        Window.Callback, KeyEvent.Callback,
        OnCreateContextMenuListener, ComponentCallbacks2,
        Window.OnWindowDismissedCallback {
    

    查看ContextWrapper.java,它从Context类调用getSharedPreferences函数

    Context mBase;
    
    @Override
    public SharedPreferences getSharedPreferences(String name, int mode) {
        return mBase.getSharedPreferences(name, mode);
    }
    

    Context.java中声明为abstract函数,

    /**
     * Interface to global information about an application environment.  This is
     * an abstract class whose implementation is provided by
     * the Android system.  It
     * allows access to application-specific resources and classes, as well as
     * up-calls for application-level operations such as launching activities,
     * broadcasting and receiving intents, etc.
     */
    public abstract class Context {
    
        public abstract SharedPreferences getSharedPreferences(String name, int mode);
    
    }
    

    总而言之,SharedPreferences 在每个 Context 实现上都在 class(如每个 interface)中实现。如果我们看一下Context 的源代码中的 cmets,我们可以看到:

    这是一个抽象类,其实现由 安卓系统

    如果您想了解有关Context 的更多信息,请点击此处了解更多信息:What is Context in Android?

    【讨论】:

    • 感谢 Santiago - 它帮助我准确了解我在寻找什么,但我不知道为什么有人对我的问题投反对票。
    • 不客气。是的,我也是,但这里是 +1 给你的
    猜你喜欢
    • 1970-01-01
    • 2011-10-25
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多