以编程方式崩溃后重新启动应用程序 - Android
问题描述:
有没有办法让我的程序我的应用程序在崩溃时自动重新启动?我的应用程序只是一个简单的媒体渲染应用程序,但它偶尔会崩溃(应该是)。这是可能吗?谢谢。我的代码看起来像这样以编程方式崩溃后重新启动应用程序 - Android
public void Play(){ if(mp != null) {
mp.reset();
mp.release();
mp = null;
}
AudioRenderer mr = new AudioRenderer();
mp = mr.AudioRenderer(filePath);
}
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
}
答
这会为你做这项工作。
How to start the automatically stopped android service?
我还是不明白为什么它应该崩溃。
您在上创建了未捕获的异常
private Thread.UncaughtExceptionHandler onRuntimeError= new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread thread, Throwable ex) {
//Try starting the Activity again
};
的处理UPDATE创建,你注册一个处理程序未捕获的异常
@Override
protected void onCreate() {
super.onCreate();
Thread.setDefaultUncaughtExceptionHandler(onRuntimeError);
}
答
我可能会晚点了很多,但我找到了2合1解决方案来解决您的问题。
public void doRestart() {
Intent mStartActivity = new Intent(context, LoginActivity.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(context, mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);
}
private void appInitialization() {
defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(_unCaughtExceptionHandler);
}
//make crash report on ex.stackreport
private Thread.UncaughtExceptionHandler defaultUEH;
// handler listener
private Thread.UncaughtExceptionHandler _unCaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable ex) {
ex.printStackTrace();
doRestart();
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_index);
appInitialization();
我真的好奇......为什么应用程序应该崩溃? – Tenfour04
为什么不只是将'应该[try]'的代码包装在try/catch中并正确处理错误? – CrackerJack9
@ CrackerJack9这是不高效的。在某些情况下,例如,nullpointerexc,现在有办法处理它。重新启动后,并不好。 – alicanbatur