2015-09-13 38 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

会不会导致内存泄漏?将应用程序对象存储在静态变量中。 –