android which class provide definition to SharedPreferences interface

Deadly 提交于 2019-12-10 22:38:21

问题


if look at SharedPreferences it clearly shows it's an interface in Android SDK.

public interface SharedPreferences

Can anyone help me understand it better that which class exactly provides definition to functions of SharedPreferences?


回答1:


It is an interface, there's no mistake in android's documentation. As you can see in SharedPreferences's source code too:

public interface SharedPreferences {

Digging in android's source code, we can see that Activity extends from ContextWrapper

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

Looking at ContextWrapper.java, it calls getSharedPreferences function from Context class

Context mBase;

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

Which is declared as an abstract function in Context.java,

/**
 * 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);

}

In conclusion SharedPreferences is implemented in a class(as every interface) on every Context implementation. If we take a look at the comments in Context's source code we can see that:

This is an abstract class whose implementation is provided by the Android system

And in case that you want more information about Context, here is way more info: What is Context in Android?




回答2:


getSharedpreference() is the function of ContextWrapper class. And ContextWrapper class is extended by Every Activity class.

When we use getSharedpreference() method then it is called by context class. It is in the context class object. But it returns the Sharedpreferences object. Shared preferences is not a class it is a interface. getSharedpreference() is use only reference of this interface.



来源:https://stackoverflow.com/questions/34248686/android-which-class-provide-definition-to-sharedpreferences-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!