سؤال

i want to restart my Android Application after a crash. My Problem is that it also restarts when i want to close the application manually by calling the method: finish();

PendingIntent _pendingInt;

 @Override
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
    setContentView(R.layout.readings_main);

//create pending intent, which starts the Application
    this._pendingInt=PendingIntent.getActivity(MyApplication.getInstance().getBaseContext(), 0,
            new Intent(getIntent()), getIntent().getFlags());
    // start handler which starts pending-intent after Application-Crash
    Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(this._pendingInt, this.getApplicationContext()));
}

And my CustomExceptionHandler:

public class CustomExceptionHandler implements UncaughtExceptionHandler {

private PendingIntent _penIntent;
Context cont;

/**
 * Constructor
 * @param intent
 * @param cont
 */
public CustomExceptionHandler(PendingIntent intent, Context cont) {
    this._penIntent = intent;
    this.cont=cont;
}

public void uncaughtException(Thread t, Throwable e) {
    AlarmManager mgr = (AlarmManager) cont.getSystemService(Context.ALARM_SERVICE);
    mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 60000, this._penIntent);
    System.exit(2);
}
}

So, when i call through Menu-Option finish(), the Application starts after 1 min.

هل كانت مفيدة؟

المحلول

To be clear, you want to restart the app if it crashes, but you don't want to restart it if you close it manually. Did I get this right?

I'm not an expert on this, but my guess is that specifying a custom exception handler is delaying the system from wiping out your app until it can call onDestroy(). This means that you go through the same lifecycle regardless of how your Activity ends.

Perhaps there's a way to get around this. You can detect that your app is finishing by calling onFinishing() in onPause(). If you disable the customExceptionHandler at that point, it won't try to restart the app.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top