有没有办法让我创建一个服务来跟踪我的活动类并在崩溃后重新启动它?请注意,我不能使用未捕获的处理程序线程方法来重新启动我的应用程序。我的应用程序应该会崩溃,不用担心那部分。我的应用程序很简单,就像这样
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
}
一旦崩溃,在后台监听的服务将自动重新启动我的应用程序。有人知道这怎么可能吗?谢谢!
是的,您可以这样做,如下所述。但如果这些技术可能对实验有意义, 他们是绝对不适合生产。那将是非常丑陋和低效的。
这就是说,这是一个方法:
做你的Service
sticky or 重新交付确保它在启动一次并且没有明确停止后始终运行。
-
in your Activity
类,静态存储WeakReference
s 指向其所有正在运行的实例,并提供一种静态检查当前是否至少分配其中一个实例的方法:
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
是对不会阻止这些对象被垃圾收集的对象的引用,更多详细信息here)
然后,从你的Service
, call MyActivity.nbInstances()
时。在上次运行崩溃后,它将返回 0 a(通常很短,但理论上不可预测)MyActivity
实例。Warning:它会这样做,除非你有内存泄漏关于这个Activity
或其底层Context
因为此泄漏会阻止崩溃实例的垃圾收集。
然后你只需要启动一个新的实例Activity
从你的Service
, using startActivity(Intent)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)