How To Restart An Activity Automatically After It Crashes?
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
Service
sticky or redelivered to ensure it will always be running after having been started once and not explicitely stopped.in your
Activity
class, statically storeWeakReference
s 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
, callMyActivity.nbInstances()
from time to time. It will return 0 a (usually short but theoretically unpredictable) while after the crash of the last runningMyActivity
instance. Warning: it will do so unless you have a memory leak concerning thisActivity
or its underlyingContext
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 yourService
, usingstartActivity(Intent)
Post a Comment for "How To Restart An Activity Automatically After It Crashes?"