崩溃后以编程方式重启App - Android

时间:2011-08-29 00:19:44

标签: android sdk crash

我有没有办法让我的应用程序在崩溃时自动重启?我的应用程序只是一个简单的媒体渲染应用程序,但它偶尔崩溃(它应该)。这是可能吗?谢谢。我的代码看起来像这样

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
}

2 个答案:

答案 0 :(得分:12)

这将为你完成这项工作。

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
    };

在创建时,您为未捕获的异常注册了一个处理程序

    @Override
    protected void onCreate() { 
        super.onCreate();
        Thread.setDefaultUncaughtExceptionHandler(onRuntimeError);  
    }

答案 1 :(得分:3)

我可能会迟到很多,但我找到了解决问题的二合一解决方案。

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();