Activity崩溃后如何自动重启? [英] How to restart an Activity automatically after it crashes?
问题描述
有没有办法让我创建一个服务来跟踪我的活动类并在崩溃后重新启动它?请注意,我不能使用 uncaughthandlers 线程方法来重新启动我的应用程序.我的应用程序应该崩溃,不要担心那部分.我的应用很简单,像这样
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 is supposed to crash, don't worry about that part. My app 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
}
一旦崩溃,后台监听的服务将自动重启我的应用.有谁知道这怎么可能?谢谢!
Once this crashes, the service listening in the background will restart my app automatically. Anybody knows how this is possible? Thanks!
推荐答案
你可以这样做,是的,如下所述.但如果这些技术可能对实验有意义,它们绝对不适合生产.那将是非常丑陋和低效的.
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.
在您的 Activity
类中,静态存储指向其所有运行实例的 WeakReference
,并提供一种静态检查当前是否至少有一个实例的方法已分配:
in your Activity
class, statically store WeakReference
s pointing to all its running instances and provide a way to statically check whether at least one of them is currently allocated:
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
是对不会阻止这些对象被垃圾收集的对象的引用,更多详细信息 这里)
(WeakReference
are references to objects that do not prevent these objects to be garbage-collected, more details here)
然后,从您的
Service
不时调用MyActivity.nbInstances()
.在最后一个运行的MyActivity
实例崩溃后,它将返回 0 a(通常很短,但理论上不可预测).警告:除非你有 关于此Activity
或其底层Context
的内存泄漏,因为此泄漏会阻止崩溃实例的垃圾回收.
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.
然后,您只需使用 startActivity(Intent)
从您的 Service
启动一个新的 Activity
实例p>
Then you just have to start a new instance of your Activity
from your Service
, using startActivity(Intent)
这篇关于Activity崩溃后如何自动重启?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!