Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restarting Android app programmatically

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:

    Toast.makeText(getActivity(), "Restarting app", Toast.LENGTH_SHORT).show();
    Intent i = getActivity().getBaseContext().getPackageManager()
.getLaunchIntentForPackage(getActivity().getBaseContext().getPackageName() );
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(i);
    getActivity().finish();

The code does nothing. The finish() is the only thing working for some reason. If I remove the finish(), nothing happens. Why is that?

like image 964
Yonatan Nir Avatar asked Sep 06 '17 09:09

Yonatan Nir


2 Answers

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.

like image 199
Dmitry Smolyaninov Avatar answered Sep 22 '22 12:09

Dmitry Smolyaninov


This works with Android > 10, tested up to Android 13 (preview)

Context ctx = getApplicationContext();
PackageManager pm = ctx.getPackageManager();
Intent intent = pm.getLaunchIntentForPackage(ctx.getPackageName());
Intent mainIntent = Intent.makeRestartActivityTask(intent.getComponent());
ctx.startActivity(mainIntent);
Runtime.getRuntime().exit(0);
like image 38
grebulon Avatar answered Sep 20 '22 12:09

grebulon