2015-12-13 33 views
2

如果看看SharedPreferences它清楚地顯示它是Android SDK中的一個接口。

公共接口SharedPreferencesandroid哪個類提供SharedPreferences接口的定義

誰能幫助我更好地理解它是哪個類提供準確定義的SharedPreferences功能?

+0

這是一個界面。 –

+0

問題是關於[SharedPreferences](http://developer.android.com/reference/android/content/SharedPreferences.html)的實現,我知道它是接口,但無法找到哪個類給它定義。 –

回答

3

這是一個界面,在android的文檔中沒有錯誤。正如你在SharedPreferences的源代碼也看到:

public interface SharedPreferences { 

在Android的源代碼挖掘,我們可以看到,ActivityContextWrapper

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

看着ContextWrapper.java延伸,它要求從ContextgetSharedPreferences功能類

Context mBase; 

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

它被聲明爲abstract功能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); 

} 

總之SharedPreferences是在classContext實現來實現(因爲每個interface)。如果我們在Context的源代碼中的註釋看一看,我們可以看到:

這是一個抽象類,它的實現是由 Android系統

而如果前提是你想了解更多有關Context,這裏的方法更多信息:What is Context in Android?

+0

感謝聖地亞哥 - 它幫助我理解我正在尋找的是什麼,但我不知道爲什麼有人對我的問題低估。 –

+1

不客氣。是的,也可以,但是這裏是+1 –

1

getSharedpreference()ContextWrapper類的功能。並且每個Activity類都擴展了ContextWrapper類。

當我們使用getSharedpreference()方法時,它被上下文類調用。它在上下文類對象中。但它返回Sharedpreferences對象。 共享偏好不是一個類,它是一個接口。 getSharedpreference()僅使用此接口的引用。