1

I have an app that consumes an API. With every request, I send a header with the version of my app, the server checks it, and if the version is too low, it would throw an error back. I did it like this so that if in the future I introduce breaking changes then I can show a nice message on the app instead of just crashing

Now any request throughout the app can potentially return this error, so what I want to do is catch this globally on every request and close whichever activity is open and open a new one saying some nice message like "Please go to play store to update your app".

Is it possible to do such thing?

To recap, i want to do 2 things:

  1. From any request, generate an ObsoleteAppException through OkHttp/Retrofit

  2. Capture only this exception globally, close any activity and open a new one with the warning

If its any useful, I am using RxJava2 and retrofit

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
M Rajoy
  • 4,028
  • 14
  • 54
  • 111

2 Answers2

0

Use Thread.setDefaultUncaughtExceptionHandler in your Application class to catch all exceptions in your app and check if the app should crash or show an update message.

This article Hide your crashes gracefully (and still report them) and many other libraries can help you "Catch exception globally in Android".

As for changing current activity, there are already answers here. It basiclly tracks every activity. When you need to change current activity, just finish current one and start a new one.

This whole approach seems like a bit of overkill for your case but I don't have a better idea...Maybe a custom RxJava exception handler to catch this exception?

Dewey Reed
  • 4,353
  • 2
  • 27
  • 41
0

You can use UCE Handler to catch exceptions and present the user with options on how to handle it.

In your Project's build.gradle file:

allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}

In your Application's or Module's build.gradle file:

dependencies {
    compile 'com.github.jampez77:UCE-Handler:uce_handler:1.4.1'
}

In your Application class initialize library using builder pattern:

public class MyApplication extends Application {
    @Override 
    public void onCreate() { 
        ...
        // Initialize UCE_Handler Library
        new UCEHandler.Builder(this).build();
    }
}

Then make sure you update you manifest as follows:

<application
    android:name=".MyApplication"
jampez77
  • 5,012
  • 7
  • 32
  • 52