Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access context in a Interceptor?

Tags:

android

okhttp

I would like to save some stuff on the SharedPreferences while being on a Interceptor. I can't find a way to do it because i can't find a way to access the context on the Interceptor (so not possible to use PreferencesManager, etc).

public class CookieInterceptor implements Interceptor {

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

    PreferenceManager.getDefaultSharedPreferences(Context ??)

}}

Any ideas ?

I'm using AndroidStudio & last version of OkHttp.

Thanks ;)

like image 553
se0 Avatar asked Sep 13 '15 03:09

se0


2 Answers

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());
like image 126
user1282637 Avatar answered Nov 14 '22 01:11

user1282637


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!

like image 40
rzaaeeff Avatar answered Nov 14 '22 01:11

rzaaeeff