356

Firstly, I know that one should not really kill/restart an application on Android. In my use case, I want to factory-reset my application in a specific case where a server sends a piece of specific information to the client.

The user can only be logged in on the server with ONE instance of the application (i.e. multiple devices are not allowed). If another instance gets that "logged-in"-lock then all other instances of that user have to delete their data (factory-reset), to maintain consistency.

It is possible to forcibly get the lock because the user might delete the app and reinstall it which would result in a different instance-id and the user would not be able to free the lock anymore. Therefore it is possible to forcibly get the lock.

Because of that force-possibility, we need to always check in a concrete instance that it has the lock. That is done on (almost) each request to the server. The server might send a "wrong-lock-id". If that is detected, the client application must delete everything.


That was the use-case.

I have an Activity A that starts the Login Activity L or the app's main Activity B depending on a sharedPrefs value. After starting L or B it closes itself so that only L or B is running. So in the case that the user is logged in already B is running now.

B starts C. C calls startService for the IntentService D. That results in this stack:

(A) > B > C > D

From the onHandleIntent method of D, an event is sent to a ResultReceiver R.

R now handles that event by providing the user a dialog where he can choose to factory-reset the application (delete the database, sharedPrefs, etc.)

After the factory-reset I want to restart the application (to close all activities) and only start A again which then launches the login Activity L and finishes itself:

(A) > L

The Dialog's onClick-method looks like this:

@Override
public void onClick(DialogInterface dialog, int which) {

    // Will call onCancelListener
    MyApplication.factoryReset(); // (Deletes the database, clears sharedPrefs, etc.)
    Intent i = new Intent(MyApp.getContext(), A.class);
    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    MyApp.getContext().startActivity(i);
}

And that's the MyApp class:

public class MyApp extends Application {
    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
    }

    public static Context getContext() {
        return context;
    }

    public static void factoryReset() {
        // ...
    }
}

The problem is if I use the FLAG_ACTIVITY_NEW_TASK the Activities B and C are still running. If I hit the back button on the login Activity I see C, but I want to go back to the home screen.

If I do not set the FLAG_ACTIVITY_NEW_TASK I get the error:

07-07 12:27:12.272: ERROR/AndroidRuntime(9512): android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

I cannot use the Activities' Context, because the ServiceIntent D might also be called from a background task which is started by the AlarmManager.

So how could I solve this to the activity stack becoming (A) > L?

0

35 Answers 35

323

You can use PendingIntent to setup launching your start activity in the future and then close your application

Intent mStartActivity = new Intent(context, StartActivity.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(context, mPendingIntentId,    mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);
Sign up to request clarification or add additional context in comments.

25 Comments

This worked perfectly for me! I just used android.os.Process.killProcess(android.os.Process.myPid()); over System.exit();
On 4.3 and 4.4 devices (All I've tested) this seems to kill the current activity and then launch a new one over the top of the old one. I'm 2 activies deep (main -> prefs). Pressing back takes me to the old app, one screen back.
In my case, System.exit(0) didn't work as a transaction was rolling back. Instead I used activity.finish(); and it works just fine.
@Qulin, Guys! You cant be serious! This example is more like direction than real life example. You have to modify this snippet with starting activity name, intent id, and exit mechanics whatever you with. Do not blindly copy paste it.
This doesn't work anymore with Android Q due to new restrictions to background activities developer.android.com/preview/privacy/…
|
148

I have slightly modified Ilya_Gazman answer to use new APIs (IntentCompat is deprecated starting API 26). Runtime.getRuntime().exit(0) seems to be better than System.exit(0).

 public static void triggerRebirth(Context context) {
    PackageManager packageManager = context.getPackageManager();
    Intent intent = packageManager.getLaunchIntentForPackage(context.getPackageName());
    ComponentName componentName = intent.getComponent();
    Intent mainIntent = Intent.makeRestartActivityTask(componentName);
    // Required for API 34 and later
    // Ref: https://developer.android.com/about/versions/14/behavior-changes-14#safer-intents
    mainIntent.setPackage(context.getPackageName());
    context.startActivity(mainIntent);
    Runtime.getRuntime().exit(0);
}

16 Comments

Directly from the docs: "The call System.exit(n) is effectively equivalent to the call: Runtime.getRuntime().exit(n)". Internally, System.exit() just turns around and calls Runtime.getRuntime().exit(). There is nothing "better" about one or the other (unless one is concerned about how much typing one does or about one extra layer of method calls).
where and when call above method?
@Makvin you decide where to call it. My case was restart app after language change.
@FARID - Any of the solutions that involve calling Runtime.getRuntime().exit(0) (or System.exit(0)) will probably work. Some of my "not good" comments are for answers (such as the one by Ilya Gazman that have since been edited to incorporate such a call.
Good answer, because this solution works perfectly on newest API versions.
|
129

You can simply call:

public static void triggerRebirth(Context context, Intent nextIntent) {
    Intent intent = new Intent(context, YourClass.class);
    intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra(KEY_RESTART_INTENT, nextIntent);
    context.startActivity(intent);
    if (context instanceof Activity) {
      ((Activity) context).finish();
    }

    Runtime.getRuntime().exit(0);
}

Which is used in the ProcessPhoenix library


As an alternative:

Here's a bit improved version of @Oleg Koshkin answer.

If you really want to restart your activity including a kill of the current process, try following code. Place it in a HelperClass or where you need it.

public static void doRestart(Context c) {
        try {
            //check if the context is given
            if (c != null) {
                //fetch the packagemanager so we can get the default launch activity 
                // (you can replace this intent with any other activity if you want
                PackageManager pm = c.getPackageManager();
                //check if we got the PackageManager
                if (pm != null) {
                    //create the intent with the default start activity for your application
                    Intent mStartActivity = pm.getLaunchIntentForPackage(
                            c.getPackageName()
                    );
                    if (mStartActivity != null) {
                        mStartActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        //create a pending intent so the application is restarted after System.exit(0) was called. 
                        // We use an AlarmManager to call this intent in 100ms
                        int mPendingIntentId = 223344;
                        PendingIntent mPendingIntent = PendingIntent
                                .getActivity(c, mPendingIntentId, mStartActivity,
                                        PendingIntent.FLAG_CANCEL_CURRENT);
                        AlarmManager mgr = (AlarmManager) c.getSystemService(Context.ALARM_SERVICE);
                        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
                        //kill the application
                        System.exit(0);
                    } else {
                        Log.e(TAG, "Was not able to restart application, mStartActivity null");
                    }
                } else {
                    Log.e(TAG, "Was not able to restart application, PM null");
                }
            } else {
                Log.e(TAG, "Was not able to restart application, Context null");
            }
        } catch (Exception ex) {
            Log.e(TAG, "Was not able to restart application");
        }
    }

This will also reinitialize jni classes and all static instances.

10 Comments

This solution is nice, but it will delay for few seconds till it restarts your application, even if you decreased the 100 Millis. However, this library ProcessPhoenix by Jack Wharton does it better and quickly, but its not worth adding library for only this function inside the app.
@blueware I have updated my answer and added the code which is used inside ProcessPhonix
@mikepenz, this guy "Ilya_Gazman" did much better and without using such a library.
@blueware - Except Ilya's solution will not restart the process, so static data or loaded NDK libraries will not be correctly reinitialized.
What if my app shutsdown and doesn't restart? Various ways I've tried and the app doesn't start again. Sometimes it does, but it shutsdown again in a fraction of second. And I can't see any errors in Android Studio's logcat... Any ideas what might be the problem?
|
91

Jake Wharton recently published his ProcessPhoenix library, which does this in a reliable way. You basically only have to call:

ProcessPhoenix.triggerRebirth(context);

The library will automatically finish the calling activity, kill the application process and restart the default application activity afterwards.

12 Comments

This seems to work, but I get a crash (which gets reported). Not sure this is ideal.
I never had any issues with the lib, but feel free to report a bug at github.com/JakeWharton/ProcessPhoenix/issues
Argh, I retract my comment as I didn't look at the message close enough. I was missing an intent filter on my default launch activity. It may be worth noting the exact intent filters required.
This is so far the best solution.
@Shambhu you have to add the tag <category android:name="android.intent.category.DEFAULT" /> to your default activity <intent-filter> in the app manifest.
|
49

IntentCompat.makeMainSelectorActivity - Last tested on 11/2020

The app will be restored with the launcher activity and the old process will be killed.

Works from Api 15.

public static void restart(Context context){
    Intent mainIntent = IntentCompat.makeMainSelectorActivity(Intent.ACTION_MAIN, Intent.CATEGORY_LAUNCHER);
    mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.getApplicationContext().startActivity(mainIntent);
    System.exit(0);
}

8 Comments

This relaunches the task, but it does not restart the process, or even the Application object. Therefore any static data, data initialized during creation of the Application, or jni classes remain in their current state and are not reinitialized.
@TedHopp Oh I missed that part. I added System.exit(0); But I am not sure 100% that it will work. I will test it latter on
The best solution without using open source library to do it. Hands up and thanks for providing this answer, +1
Unfortunately, IntentCompat.makeRestartActivityTask is now deprecated. If you inspect the source code, it's as simple as simply adding the flags Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK.
see answer below for a full up-to-date function: stackoverflow.com/a/46848226/1069083
|
39

My solution doesn't restart the process/application. It only lets the app "restart" the home activity (and dismiss all other activities). It looks like a restart to users, but the process is the same. I think in some cases people want to achieve this effect, so I just leave it here FYI.

public void restart(){
    Intent intent = new Intent(this, YourHomeActivity.class);
    this.startActivity(intent);
    this.finishAffinity();
}

2 Comments

You are awesome bro :D
Tried every answers. But only your code is worked. Thanks
36

The only code that did not trigger "Your app has closed unexpectedly" is as follows. It's also non-deprecated code that doesn't require an external library. It also doesn't require a timer.

public static void triggerRebirth(Context context, Class myClass) {
    Intent intent = new Intent(context, myClass);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    context.startActivity(intent);
    Runtime.getRuntime().exit(0);
}

1 Comment

Thank you, this works great for closing custom chrome tabs and logging into the application
30

I've found that this works on API 29 and later - for the purpose of killing and restarting the app as if the user had launched it when it wasn't running.

public void restartApplication(final @NonNull Activity activity) {
   // Systems at 29/Q and later don't allow relaunch, but System.exit(0) on
   // all supported systems will relaunch ... but by killing the process, then
   // restarting the process with the back stack intact. We must make sure that
   // the launch activity is the only thing in the back stack before exiting.
   final PackageManager pm = activity.getPackageManager();
   final Intent intent = pm.getLaunchIntentForPackage(activity.getPackageName());
   activity.finishAffinity(); // Finishes all activities.
   activity.startActivity(intent);    // Start the launch activity
   System.exit(0);    // System finishes and automatically relaunches us.
}

That was done when the launcher activity in the app has this:

<intent-filter>
    <action android:name="android.intent.action.VIEW"/>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

I've seen comments claiming that a category of DEFAULT is needed, but I haven't found that to be the case. I have confirmed that the Application object in my app is re-created, so I believe that the process really has been killed and restarted.

The only purpose for which I use this is to restart the app after the user has enabled or disabled crash reporting for Firebase Crashlytics. According to their docs, the app has to be restarted (process killed and re-created) for that change to take effect.

2 Comments

DEFAULT is needed if your single APK is exposing more than one launcher icons
Not working. Android version 11.
28

There is a really nice trick. My problem was that some really old C++ jni library leaked resources. At some point, it stopped functioning. The user tried to exit the app and launch it again -- with no result, because finishing an activity is not the same as finishing (or killing) the process. (By the way, the user could go to the list of the running applications and stop it from there -- this would work, but the users just do not know how to terminate applications.)

If you want to observe the effect of this feature, add a static variable to your activity and increment it each, say, button press. If you exit the application activity and then invoke the application again, this static variable will keep its value. (If the application really was exited, the variable would be assigned the initial value.)

(And I have to comment on why I did not want to fix the bug instead. The library was written decades ago and leaked resources ever since. The management believes it always worked. The cost of providing a fix instead of a workaround... I think, you get the idea.)

Now, how could I reset a jni shared (a.k.a. dynamic, .so) library to the initial state? I chose to restart application as a new process.

The trick is that System.exit() closes the current activity and Android recreates the application with one activity less.

So the code is:

/** This activity shows nothing; instead, it restarts the android process */
public class MagicAppRestart extends Activity {
    // Do not forget to add it to AndroidManifest.xml
    // <activity android:name="your.package.name.MagicAppRestart"/>
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        System.exit(0);
    }
    public static void doRestart(Activity anyActivity) {
        anyActivity.startActivity(new Intent(anyActivity.getApplicationContext(), MagicAppRestart.class));
    }
}

The calling activity just executes the code MagicAppRestart.doRestart(this);, the calling activity's onPause() is executed, and then the process is re-created. And do not forget to mention this activity in AndroidManifest.xml

The advantage of this method is that there is no delays.

UPD: it worked in Android 2.x, but in Android 4 something has changed.

5 Comments

i used activity.startActivity(i); System.exit(0); genius solution
This solution closes the app for me, but it doesn't restart. At least on Android 4.3.
On samsung galaxy mega android 4.2.2 It causes infinite loop of restart. So the app wont start again.
@Gunhan 1) what happens if you replace System.exit(0) by android.os.Process.killProcess(android.os.Process.myPid());? 2) an infinite loop most likely means that they do not remove the topmost activity when they restart an app. In principle, you can add a static boolean variable, set it to true before invoking the restart activity, and after the restart it will be false. Thus the activity can find out whether or not the restart has already happened (and if it has happened, just finish()). OTOH, your report means that the trick does not work identically on all devices.
@Gunham If you are starting the same activity that is causing the restart then it will be infinite loop on any device.
16

Ok, I refactored my app and I will not finish A automatically. I let this run always and finish it through the onActivityResult event. In this way I can use the FLAG_ACTIVITY_CLEAR_TOP + FLAG_ACTIVITY_NEW_TASK flags to get what I want:

public class A extends Activity {

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        finish();
    }

    protected void onResume() {
        super.onResume();
        // ...
        if (loggedIn) {
            startActivityForResult(new Intent(this, MainActivity.class), 0);
        } else {
            startActivityForResult(new Intent(this, LoginActivity.class), 0);
        }
    }
}

and in the ResultReceiver

@Override
public void onClick(DialogInterface dialog, int which) {
    MyApp.factoryReset();
    Intent i = new Intent(MyApp.getContext(), A.class);
    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    MyApp.getContext().startActivity(i);
}

Thanks anyway!

1 Comment

This will not restart the application, only re-create the classes. Thus, any static variables within the classes will retain values from previous runs.
13
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);

1 Comment

This will not restart the application, only re-create the classes. Thus, any static variables within the classes will retain values from previous runs.
10

For Kotlin - 2023 Edition

fun Context.restartApplication() {
    val intent = packageManager.getLaunchIntentForPackage(packageName)
    val componentName = intent?.component
    val mainIntent = Intent.makeRestartActivityTask(componentName)
    startActivity(mainIntent)
    Runtime.getRuntime().exit(0)
}

1 Comment

Does this restart at OS level? Is there a way to add a delay for restarting the app.
9

The best way to fully restart an app is to relaunch it, not just to jump to an activity with FLAG_ACTIVITY_CLEAR_TOP and FLAG_ACTIVITY_NEW_TASK. So my solution is to do it from your app or even from another app, the only condition is to know the app package name (example: 'com.example.myProject')

 public static void forceRunApp(Context context, String packageApp){
    Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(packageApp);
    launchIntent.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(launchIntent);
}

Example of usage restart or launch appA from appB:

forceRunApp(mContext, "com.example.myProject.appA");

You can check if the app is running:

 public static boolean isAppRunning(Context context, String packageApp){
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();
    for (int i = 0; i < procInfos.size(); i++) {
        if (procInfos.get(i).processName.equals(packageApp)) {
           return true;
        }
    }
    return false;
}

Note: I know this answer is a bit out of topic, but it can be really helpful for somebody.

Comments

7

Still Working Now

 public void resetApplication() {
    Intent resetApplicationIntent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
    if (resetApplicationIntent != null) {
        resetApplicationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    }
    context.startActivity(resetApplicationIntent);
    ((Activity) context).overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}

1 Comment

That restarts the activity (and the task stack), but doesn't restart the entire app. Specifically, if you have an Application subclass, or if you have static classes with state data, those objects will not be re-initialized.
7

This code passed the Android 8-13 test

public void restartApp() {
    Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName() );  
    startActivity(Intent.makeRestartActivityTask(i.getComponent()));  
    Runtime.getRuntime().exit(0);
}

Comments

6

My best way to restart application is to use finishAffinity();
Since, finishAffinity(); can be used on JELLY BEAN versions only, so we can use ActivityCompat.finishAffinity(YourCurrentActivity.this); for lower versions.

Then use Intent to launch first activity, so the code will look like this:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
    finishAffinity();
    Intent intent = new Intent(getApplicationContext(), YourFirstActivity.class);
    startActivity(intent);
} else {
    ActivityCompat.finishAffinity(YourCurrentActivity.this);
    Intent intent = new Intent(getApplicationContext(), YourFirstActivity.class);
    startActivity(intent);
}

Hope it helps.

1 Comment

This ends all activities in the current task, but it does not restart the process, or even recreate the Application object. Therefore any static data, data initialized during creation of the Application, or by jni classes, remain in their current state and are not reinitialized.
4

Kotlin version of this answer:

val intent = Intent(this, YourActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(intent)
Runtime.getRuntime().exit(0)

Comments

2

Try using FLAG_ACTIVITY_CLEAR_TASK

2 Comments

hm developing for 2.1: Intent.FLAG_ACTIVITY_CLEAR_TASK cannot be resolved
2
fun triggerRestart(context: Activity) {
    val intent = Intent(context, MainActivity::class.java)
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    context.startActivity(intent)
    if (context is Activity) {
        (context as Activity).finish()
    }
    Runtime.getRuntime().exit(0)
}

Comments

2

I got this way.

Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage( 
 getBaseContext().getPackageName() );
 i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 startActivity(i);
 finish();

Comments

1

You can use startInstrumentation method of Activity. You need implement empty Instrumentation and pointed in manifest. After that you can call this method for restart your app. Like this:

try {           
    InstrumentationInfo info = getPackageManager().queryInstrumentation(getPackageName(), 0).get(0);
    ComponentName component = new ComponentName(this, Class.forName(info.name));
    startInstrumentation(component, null, null);
} catch (Throwable e) {             
    new RuntimeException("Failed restart with Instrumentation", e);
}

I get Instrumentation class name dynamically but you can hardcode it. Some like this:

try {           
    startInstrumentation(new ComponentName(this, RebootInstrumentation.class), null, null); 
} catch (Throwable e) {             
    new RuntimeException("Failed restart with Instrumentation", e);
}

Call startInstrumentation make reload of your app. Read description of this method. But it can be not safe if acting like kill app.

Comments

1

The application I'm working on has to give the user the possibility to choose which fragments to display (fragments are dynamically changed at run-time). The best solution for me was to restart completely the application.

So I tried plenty of solutions and none of them has worked for me, but this:

final Intent mStartActivity = new Intent(SettingsActivity.this, Splash.class);
final int mPendingIntentId = 123456;
final PendingIntent mPendingIntent = PendingIntent.getActivity(SettingsActivity.this, mPendingIntentId, mStartActivity,
                    PendingIntent.FLAG_CANCEL_CURRENT);
final AlarmManager mgr = (AlarmManager) SettingsActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
this.finishAffinity(); //notice here
Runtime.getRuntime().exit(0); //notice here

Hoping that is going to help someone else!

1 Comment

Good thought to move to Splash. We can move directly to splash screen by using a normal intent too right.
1

Use:

navigateUpTo(new Intent(this, MainActivity.class));

It works starting from API level 16 (4.1), I believe.

Comments

1

Directly start the initial screen with FLAG_ACTIVITY_CLEAR_TASK and FLAG_ACTIVITY_NEW_TASK.

Comments

0

I had to add a Handler to delay the exit:

 mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 200, mPendingIntent);
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Runtime.getRuntime().exit(0);
            }
        }, 100);

1 Comment

Why would you want to delay the kill part. There's no basis for this answer, added 6 years after better answers.
0

try this:

Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

1 Comment

As with every other answer here already suggesting the same thing, this will not restart the application, only re-create the classes. Thus, any static data within the process will not be reset.
0

With the Process Phoenix library. The Activity you want to relaunch is named "A".

Java flavor

// Java
public void restart(){
    ProcessPhoenix.triggerRebirth(context);
}

Kotlin flavor

// kotlin
fun restart() {
    ProcessPhoenix.triggerRebirth(context)
}

2 Comments

This has the unfortunate result of making your debugger disconnect.
@S.V. - AFAIK, ANY solution that kills the process (in order to restart in a clean state), will disconnect the debugger. Consider that "symptom" a sign that this approach is truly giving you a fresh start.
0

Apply delay restart

startDelay Startup delay (in milliseconds)

 public static void reStartApp(Context context, long startDelay) {
    //Obtain the startup Intent of the application with the package name of the application
    Intent intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
    PendingIntent restartIntent = PendingIntent.getActivity(context.getApplicationContext(), -1, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    if (mgr != null) {
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + startDelay, restartIntent);
    }
}

Comments

0
val i = baseContext.packageManager.getLaunchIntentForPackage(baseContext.packageName)
i!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
startActivity(i)
finish()

Comments

0

Here’s the working code for scheduling an app restart, which functions as expected on devices running Android 12 (API Level 31) and below. This code has not been tested on devices running versions above API Level 31

private const val PENDING_INTENT_ID = 223344
private const val RESTART_DELAY_MS = 100L  // 100 milliseconds

    // Schedules an app restart by creating a PendingIntent that will trigger the app's launch after a short delay.
    fun scheduleAppRestart(context: Context) {
        val launchIntent = createAppLaunchIntent(context)
        launchIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        Timber.d("App restart intent: $launchIntent")

        val pendingIntent = PendingIntent.getActivity(
            context,
            PENDING_INTENT_ID,
            launchIntent,
            PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE
        )

        val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        alarmManager.set(
            AlarmManager.RTC, System.currentTimeMillis() + RESTART_DELAY_MS, pendingIntent
        )
    }

    // Creates an Intent to launch the app's main activity or default activity, considering Android TV (Leanback) support.
    private fun createAppLaunchIntent(context: Context): Intent {
        val packageName = context.packageName
        val packageManager = context.packageManager

        // Try getting the Leanback launch intent for Android TV apps
        val launchIntent =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && packageManager.hasSystemFeature(
                    PackageManager.FEATURE_LEANBACK
                )
            ) {
                packageManager.getLeanbackLaunchIntentForPackage(packageName)
            } else {
                packageManager.getLaunchIntentForPackage(packageName)
            }

        return launchIntent ?: throw IllegalStateException(
            "Unable to determine default activity for $packageName. Does an activity specify the DEFAULT category in its intent filter?"
        )
    }

Usage:

if (isAppInForeground) {
    scheduleAppRestart(applicationContext)  // Schedule app restart if it's in the foreground
}

exitProcess(0) // exit process optionally

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.