How to access context in a Interceptor?

You should not keep static instance of context, since it will lead to memory leak. Instead, you can change your architecture a bit to be able to send context as a parameter to the 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();
    }
}

Then you can use that context instance in your Interceptor class.

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);

    }
}

Good luck!


You can create a class that allows you to retrieve the context from anywhere (i.e. your interceptor):

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();
    }
}

Then add this to your manifest like this:

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

And then in your interceptor, do this:

PreferenceManager.getDefaultSharedPreferences(MyApp.getContext());

Tags:

Android

Okhttp