Restarting Android app programmatically

前端 未结 9 2111
独厮守ぢ
独厮守ぢ 2021-02-03 12:14

This is a follow up question to this question:

Force application to restart on first activity

I am trying to restart my application from a fragment like that:

9条回答
  •  既然无缘
    2021-02-03 12:40

    If you just consider to switch to your starting Activity, refer to Ricardo's answer. But this approach won't reset static context of your app and won't rebuild the Application class, so the app won't be really restarted.

    If you want to completely restart your app, I can advise more radical way, using PendingIntent.

    private void restartApp() {
        Intent intent = new Intent(getApplicationContext(), YourStarterActivity.class);
        int mPendingIntentId = MAGICAL_NUMBER;
        PendingIntent mPendingIntent = PendingIntent.getActivity(getApplicationContext(), mPendingIntentId, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager mgr = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
        System.exit(0);
    }
    

    P.S. Tried your code in my project - works well with and without finish(). So maybe you have something specific about your Activity or Fragment, you haven't written.

提交回复
热议问题