Android - Override "Sorry, the application has stopped" Dialogue with DefaultUncaughtExceptionHandler

I want the app to automatically restart when it crashes. Currently I have achieved this with the DefaultUncaughtExceptionHandler, but sometimes when the application crashes, it sends the "Sorry, the application has stopped" dialog box and it does not restart. How can I avoid the dialogue and just restart the application every time it crashes?

Thank.

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

      

+3


source to share





All Articles