Skip to content Skip to sidebar Skip to footer

How To Restart An Activity Automatically After It Crashes?

Is there a way for me to create a service to track my activity class and restart it after a crash? Note that i CANNOT use uncaughthandlers thread method to restart my app. My app i

Solution 1:

You can do that, yes, as explained below. But if such techniques may make sense for experiments, they are definitely not suitable for production. That would be awfully ugly and unefficient.

This said, here is a way to go:

  • Make your Servicesticky or redelivered to ensure it will always be running after having been started once and not explicitely stopped.

  • in your Activity class, statically store WeakReferences pointing to all its running instances and provide a way to statically check whether at least one of them is currently allocated:

    publicclassMyActivityextendsActivity {
        privatestatic ArrayList<WeakReference<MyActivity >> sMyInstances = new ArrayList<WeakReference<MyActivity >>();
    
        publicMyActivity() {
            sMyInstances.add(new WeakReference<MyActivity >(this));            
        }
    
        privatestaticintnbInstances() {
            int ret = 0;
            final int size = sMyInstances.size();
    
            for (int ctr = 0; ctr < size; ++ctr) {
                if (sMyInstances.get(ctr).get() != null) {
                    ret++; 
                }
            }
    
            return ret;
        }
    }
    

(WeakReference are references to objects that do not prevent these objects to be garbage-collected, more details here)

  • Then, from your Service, call MyActivity.nbInstances() from time to time. It will return 0 a (usually short but theoretically unpredictable) while after the crash of the last running MyActivity instance. Warning: it will do so unless you have a memory leak concerning this Activity or its underlying Context as this leak would prevent the garbage collection of the instance that crashed.

  • Then you just have to start a new instance of your Activity from your Service, using startActivity(Intent)

Post a Comment for "How To Restart An Activity Automatically After It Crashes?"