How to restart Activity automatically after its failure?

Is there a way to create a service to track my activity class and restart it after a crash? Please note that I CAN NOT use the uncaughthandlers thread method to restart my application. My application should crash, do not worry about this part. My application is something simple like this

private class AudioRenderer extends Activity { private MediaPlayer AudioRenderer(String filePath) { File location = new File(filePath); Uri path = Uri.fromFile(location); mp= MediaPlayer.create(this, path); } return mp } 

As soon as this happens, the service listening in the background will automatically restart my application. Does anyone know how this is possible? Thanks!

+1
source share
1 answer

You can do this, yes, as explained below. But if such methods may make sense for experiments , they are definitely not suitable for production . That would be terribly ugly and inefficient.

This talks about how to do this:

  • Make a Service sticky or redelivered to ensure that it will always start after it has been started once and will not be explicitly stopped.

  • in your Activity class, statically save WeakReference , pointing to all running instances and providing a way to statically check at least one of them is currently highlighted:

     public class MyActivity extends Activity { private static ArrayList<WeakReference<MyActivity >> sMyInstances = new ArrayList<WeakReference<MyActivity >>(); public MyActivity() { sMyInstances.add(new WeakReference<MyActivity >(this)); } private static int nbInstances() { 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 links to objects that do not interfere with garbage collection of these objects, more details here )

  • Then from your Service , call MyActivity.nbInstances() from time to time. It will return 0 a (usually short, but theoretically unpredictable), and after the crash of the last launch of the MyActivity instance. Warning : this will be done if you do not have a memory leak regarding this Activity or its underlying Context as this leak would prevent garbage collection of the instance that crashed.

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

+3
source

All Articles