如何在Interceptor中访问上下文?

se0*_*se0 14 android okhttp

我想在拦截器上保存SharedPreferences上的一些东西.我找不到办法,因为我找不到一种方法来访问Interceptor上的上下文(所以不可能使用PreferencesManager等).

public class CookieInterceptor implements Interceptor {

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

    PreferenceManager.getDefaultSharedPreferences(Context ??)

}}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗 ?

我正在使用AndroidStudio和OkHttp的最新版本.

谢谢 ;)

use*_*637 7

您可以创建一个类,允许您从任何地方(即您的拦截器)检索上下文:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后将其添加到您的清单中,如下所示:

<application
    android:name="com.example.app.MyApp"
Run Code Online (Sandbox Code Playgroud)

然后在您的拦截器中,执行以下操作:

PreferenceManager.getDefaultSharedPreferences(MyApp.getContext());
Run Code Online (Sandbox Code Playgroud)

  • 会不会导致内存泄漏?将应用程序对象存储在静态变量中。 (7认同)

rza*_*eff 6

您不应保留上下文的静态实例,因为它会导致内存泄漏。取而代之的是,您可以稍微更改体系结构,以便将上下文作为参数发送给Interceptor。

// in your network operations class
// where you create OkHttp instance
// and add interceptor
public class NetworkOperations {
    private Context context;

    public NetworkOperations(Context context) {
        this.context = context;

    OkHttpClient client = new OkHttpClient.Builder()
                // ... some code here
                .addInterceptor(new CookieInterceptor(context))
                // ... some code here
                .build();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以在Interceptor类中使用该上下文实例。

public class CookieInterceptor implements Interceptor {
    private Context context;

    public CookieInterceptor(Context context) {
        this.context = context;
    }

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

        PreferenceManager.getDefaultSharedPreferences(context)

    }
}
Run Code Online (Sandbox Code Playgroud)

祝好运!