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?