如何在拦截器中访问上下文? [英] How to access context in a Interceptor?
本文介绍了如何在拦截器中访问上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在拦截器上保存一些东西到SharedPreferences上. 我找不到方法,因为我找不到访问拦截器上的上下文的方法(因此无法使用PreferencesManager等).
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 ??)
}}
有什么想法吗?
我正在使用AndroidStudio& OkHttp的最新版本.
I'm using AndroidStudio & last version of OkHttp.
谢谢;)
推荐答案
您可以创建一个类,使您可以从任何地方(即您的拦截器)检索上下文:
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());
这篇关于如何在拦截器中访问上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文