Tuesday, 22 November 2016

How to restart android app after exception/crash




put below code into your Application:


public void onCreate() {
    super.onCreate();
    setupHandler4UncaughtException();
}


private void setupHandler4UncaughtException () {
    Thread.setDefaultUncaughtExceptionHandler (new Thread.UncaughtExceptionHandler() {
        @Override        
        public void uncaughtException (Thread thread, Throwable e) {
            handleUncaughtException (thread, e);        
        }
    });}

public void handleUncaughtException (Thread thread, Throwable e) {
    IAnalyticsService analyticsService = ServicesRegestory.getInstance().getService(IAnalyticsService.class);
    if (analyticsService != null) {
        analyticsService.sendEvent(Constants.ANALYTICS_EVENT_APP_ERROR, e.getMessage());
    }

    Log.e(TAG, "APP Error", e);
    Intent intent = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName() );
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(this.getBaseContext(), 0, intent, intent.getFlags());
    
    AlarmManager mgr = (AlarmManager) this.getBaseContext().getSystemService(Context.ALARM_SERVICE);
    mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, pendingIntent);
    System.exit(2);
}






Then you can put below code into your code to test: (better to call this function buy a button click, or in your Activity onCreate function)

throw new RuntimeException("test crucsh");

http://chintanrathod.com/auto-restart-application-after-crash-forceclose-in-android/



No comments:

Post a comment