Activity崩溃后如何自动重启?
有没有办法让我创建一个服务来跟踪我的活动类并在崩溃后重新启动它?请注意,我不能使用未捕获的处理程序线程方法来重新启动我的应用程序。我的应用程序应该会崩溃,不用担心那部分。我的应用程序很简单,就像这样
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
}
一旦崩溃,后台监听的服务将自动重新启动我的应用程序。有人知道这怎么可能吗?谢谢!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,您可以这样做,如下所述。但是,如果此类技术对于实验可能有意义,那么它们绝对不适合生产。那将是非常丑陋和低效的。
也就是说,这里有一个方法:
Make your
Service
粘性 或重新传送以确保它会启动一次后始终运行,并且不会明确停止。在您的
Activity
类中,静态存储指向其所有正在运行的实例的WeakReference
,并提供一种方法来静态检查当前是否至少分配了其中一个实例:< /p>WeakReference
是对不会阻止这些对象被垃圾收集的对象的引用,更多详细信息此处)然后,从您的
Service
中,不时调用MyActivity.nbInstances()
。在最后一个运行的 MyActivity 实例崩溃后,它将返回 0 a(通常很短,但理论上不可预测)。 警告:除非您有 ,否则它会这样做关于此Activity
或其底层Context
的内存泄漏,因为此泄漏会阻止崩溃实例的垃圾回收。然后,您只需使用
startActivity(Intent)
从Service
启动Activity
的新实例,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:(
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)