2015-09-13 34 views
6

我想在攔截器上保存一些在SharedPreferences上的東西。 我找不到一種方法來做到這一點,因爲我無法找到訪問Interceptor上下文的方法(因此無法使用PreferencesManager等)。如何訪問攔截器中的上下文?

public class CookieInterceptor implements Interceptor { 

@Override public Response intercept(Chain chain) throws IOException { 

    PreferenceManager.getDefaultSharedPreferences(Context ??) 

}} 

任何想法?

我正在使用AndroidStudio & OkHttp的最新版本。

感謝;)

回答

3

您可以創建一個類,允許你從任何地方獲取上下文(即你的攔截):

public class MyApp extends Application { 
    private static MyApp instance; 

    public static MyApp getInstance() { 
     return instance; 
    } 

    public static Context getContext(){ 
     return instance; 
    } 

    @Override 
    public void onCreate() { 
     instance = this; 
     super.onCreate(); 
    } 
} 

那麼這個像這樣添加到您的清單:

<application 
    android:name="com.example.app.MyApp" 

,然後在攔截器,這樣做:

PreferenceManager.getDefaultSharedPreferences(MyApp.getContext()); 
+0

會不會導致內存泄漏?將應用程序對象存儲在靜態變量中。 –