Restarting Android app programmatically
Asked Answered
D

11

18

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?

Dunford answered 6/9, 2017 at 9:1 Comment(4)
#17294928Wonacott
Possible duplicate of How do I programmatically "restart" an Android app?Tieck
Where are you executing this code? Is this in an Activity? If so, which one? Please post your manifest. What exactly are you trying to accomplish?Scatterbrain
Have you looked into finishAffinity?Qulllon
H
22

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.

Hezekiah answered 6/9, 2017 at 9:20 Comment(4)
You should consider using android.os.Process.killProcess(android.os.Process.myPid()); as wellQulllon
This solution works well with 1 problem. Normally our application exits if the android back button pressed from the main activity. However with thie solution I need to press the back button so many times as many time the application was restarted. Any idea?Certificate
it is not working in Android Q. Can you update the answer? found this developer.android.com/preview/privacy/… article but couldn't found a solution.Streit
I confirm, this solution works on Android 9 but does not work on Android 10 (Android Q). I tested on a Pixel XL 4 with no luck... except this way: If I launch the app from the "App Info" page using the "Open" button, then it works, respawning the app as expected! ...but that's a very specific use case! :PHudspeth
M
27

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);
Merle answered 8/3, 2022 at 9:35 Comment(3)
This is beautifully simple and works well in my tests on Android-12.Hydrolysate
It's perfect and works very smoothly. I suggest everyone to use this method. I tested in android 7 it works well.Asperity
Works in Android 14 (API 34)Valval
H
22

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.

Hezekiah answered 6/9, 2017 at 9:20 Comment(4)
You should consider using android.os.Process.killProcess(android.os.Process.myPid()); as wellQulllon
This solution works well with 1 problem. Normally our application exits if the android back button pressed from the main activity. However with thie solution I need to press the back button so many times as many time the application was restarted. Any idea?Certificate
it is not working in Android Q. Can you update the answer? found this developer.android.com/preview/privacy/… article but couldn't found a solution.Streit
I confirm, this solution works on Android 9 but does not work on Android 10 (Android Q). I tested on a Pixel XL 4 with no luck... except this way: If I launch the app from the "App Info" page using the "Open" button, then it works, respawning the app as expected! ...but that's a very specific use case! :PHudspeth
M
8

Please refer below code

    Intent intent = new Intent(this, YourHomeActivity.class);
    this.startActivity(intent);
    this.finishAffinity();

It is starting your home activity and dismiss all other activities. It looks like a restart to users, but the process is the same.

Midge answered 6/9, 2017 at 9:12 Comment(0)
L
6

try this one

 Intent intent = getActivity().getBaseContext().getPackageManager().getLaunchIntentForPackage(getActivity().getBaseContext().getPackageName() );
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);
                    android.os.Process.killProcess(android.os.Process.myPid());
                    System.exit(0);
Lilt answered 6/9, 2017 at 9:14 Comment(2)
Why do you have these two specific intent flags?Qulllon
Be careful, #11035828Shf
F
4

Tray this

getActivity().finish();
getActivity().startActivity(new Intent(getContext(), Main.class));
getActivity().finishAffinity();

where finishAffinity() close all other Intents

Feces answered 16/2, 2019 at 8:32 Comment(0)
I
3
Intent i = getBaseContext().getPackageManager()
             .getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
finish();
startActivity(i);

You can refer to previous discussion (click here)

Inadmissible answered 6/9, 2017 at 9:7 Comment(0)
F
3

As the accepted answer doesn't seem to work on Android Q anymore due to the new background launch limitations, let me add my own solution:

startActivity(
    Intent(applicationContext, MainActivity::class.java)
)
System.exit(0)

Although it looks strange, it works very reliably for me, as the intent takes longer to fire than the system exit does. Plus, it is fired from the main thread, so Android Q won't complain.

Farnesol answered 10/6, 2019 at 12:3 Comment(0)
A
2

Once you add this FLAGSto the intent

i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

and call startActivity(), it will clear all the other activities including the one you call this from, so calling finish() after startActivity() will close the started activity.

Basically, remove getActivity().finish().

Accoucheur answered 6/9, 2017 at 9:6 Comment(1)
I specifically wrote in the question: "If I remove the finish(), nothing happens."Dunford
O
1

This works for me 'Activity.recreate()'

activity?.recreate()
Oldline answered 5/1, 2023 at 6:0 Comment(2)
This method does not result in restarting the application. This simply recreates the activity (the same as configuration change). If the application is not top task activity - you will be left with plenty of elements in the history.Ballyhoo
This solution was perfect for me. I had some lateinet variable in my activity and it was crashes. I had problem with a webView load but recreate() (kotlin) solved my problemTitbit
I
0

try using below lines:

Intent i = getBaseContext().getPackageManager()
                .getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
ActivityCompat.finishAfterTransition(YourCurrentActivity.this);

ActivityCompat.finishAfterTransition(YourCurrentActivity.this); this line clear the instance after creating another activity

Integer answered 6/9, 2017 at 9:7 Comment(1)
The method finishAfterTransition(Activity) is undefined for the type ActivityCompatDunford
S
0

Add this code as per your activity and your app will restart. This code is in kotlin.

val intent = Intent(baseContext, MainActivity::class.java)
val pendingIntentId = 101
val pendingIntent = PendingIntent.getActivity(this, pendingIntentId,intent, PendingIntent.FLAG_CANCEL_CURRENT)
val alarmManager = (this.getSystemService(Context.ALARM_SERVICE)) as AlarmManager
alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + 100, pendingIntent)
exitProcess(0)
Shortstop answered 7/8, 2019 at 11:39 Comment(1)
Since Android 10 you can't launch from background, use my method below. See: developer.android.com/guide/components/activities/…Merle

© 2022 - 2024 — McMap. All rights reserved.