Android - Override "Unfortunately app has stopped" Dialog with DefaultUncaughtExceptionHandler

465 views Asked by At

I want an app to auto restart when it crashes. I currently have achieved this with a DefaultUncaughtExceptionHandler but sometimes when the app crashes it sends the Dialog "Unfortunately app has stopped" and it doesn't restart. How can I avoid the Dialog and just restart the app everytime it crashes?

Thanks.

@Override
public void uncaughtException(Thread thread, Throwable ex) {

    try {

        Intent intent = new Intent(activity, FrontActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(
                application.getBaseContext(), 0, intent,
                PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_CANCEL_CURRENT);

        //Following code will restart your application after 2 seconds
        AlarmManager mgr = (AlarmManager) application.getBaseContext()
                .getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000,
                pendingIntent);

        //This will finish your activity manually
        activity.finish();

        //This will stop your application and take out from it.
        System.exit(2);

    } catch (RuntimeException e) {
        e.printStackTrace();
    }
}
0

There are 0 answers