Skip to content

Instantly share code, notes, and snippets.

@artzmb
Last active March 6, 2018 16:51
Show Gist options
  • Save artzmb/c88e9931df40304a4d779fffedbd5884 to your computer and use it in GitHub Desktop.
Save artzmb/c88e9931df40304a4d779fffedbd5884 to your computer and use it in GitHub Desktop.
HTTP Unauthorized interceptor
...
<service android:name=".background.interceptor.HttpUnauthorizedJobIntentService"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="false" />
...
public class HttpUnauthorizedJobIntentService extends JobIntentService {
private static final int JOB_ID = 1001;
@Inject DataManager dataManager;
private final Handler handler = new Handler();
public static void enqueueWork(Context context) {
enqueueWork(context, HttpUnauthorizedJobIntentService.class, JOB_ID, new Intent());
}
@Override
public void onCreate() {
super.onCreate();
((NimbApplication) getApplicationContext()).getComponent().inject(this);
}
@Override
protected void onHandleWork(@NonNull Intent intent) {
if (dataManager.isAuthorized()) {
dataManager.logoutLocalAndClearLocalData();
startLogoutActivityIfNeeded();
}
}
private void startLogoutActivityIfNeeded() {
if (AndroidUtil.isAppInForeground()) {
handler.post(() -> {
Toast.makeText(this, R.string.http_unauthorized, Toast.LENGTH_SHORT).show();
Intent startActivity = StartActivity.createStartActivity(this);
startActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startActivity);
});
}
}
}
@Singleton
public class UnauthorizedInterceptor implements Interceptor {
private Context context;
@Inject
public UnauthorizedInterceptor(@ApplicationContext Context context) {
this.context = context;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
if (response.code() == HttpURLConnection.HTTP_UNAUTHORIZED) {
HttpUnauthorizedJobIntentService.enqueueWork(context);
}
return response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment