如果看SharedPreferences它清楚地表明它是 Android SDK 中的一个接口(interface)。
公共(public)接口(interface) SharedPreferences
谁能帮助我更好地理解哪个类准确地提供了SharedPreferences 函数的定义? ?
最佳答案
是接口(interface),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
源代码中的注释,我们可以看到:
This is an abstract class whose implementation is provided by the Android system
如果您想了解有关 Context
的更多信息,这里有更多信息:What is Context in Android?
关于android 哪个类提供对 SharedPreferences 接口(interface)的定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34248686/