The Context parameter passage problem in android [Interceptor]

萝らか妹 提交于 2019-12-11 02:55:28

问题


I'm new in android development and used to develop in JavaScript. A common practice there is to implement an interceptor to add Authorization header. In my current application is not different. In this new world to me, SharedPreferences is quite equivalent to LocalStorage. But to access the first one I have to use a Context.

Here is my problem: to get a token, stored in SharedPreferences, being inside the intercept method, I must pass a Context to the Interceptor, but the flow 'til there has many classes: a service, a Retrofit handler, a okhttp3 client, and just then Interceptor itself.

I'm digging it for awhile, and the two approaches I've found are: pass the Context through all this flow as parameter or create a "God" class only to keep the Application Context at hand as static method.

For now, I'm using the first one as you can see below.


public class APIRESTInterceptor implements Interceptor {

    private static final List<String> noAuthRequirements =  new ArrayList<>(Arrays.asList("/api/app/login", "/api/app/token/refresh"));
    private static Context context;

    public APIRESTInterceptor(Context context) {
        setContext(context);
    }

    public static void setContext(Context context) {
        APIRESTInterceptor.context = context;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        String requestPath = request.url().encodedPath();

        if (!noAuthRequirements.contains(requestPath)) {
            String accessToken = SessionUtils.readOfSharedPreferences(context).getAccess();
            request = request.newBuilder().addHeader("Authorization", accessToken).build();
        }

        return  chain.proceed(request);
    }
}

What I want from you, people: a simpler strategy, more like what is done in JavaScript to access LocalStorage, despite the mess there (sorry). Sumarizing, I don't want to pass it as parameter neither this "God" class. Is there a third approach?

来源:https://stackoverflow.com/questions/56961903/the-context-parameter-passage-problem-in-android-interceptor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!