How do I programmatically “restart” an Android app?

后端 未结 26 1975
小鲜肉
小鲜肉 2020-11-22 12:42

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 s

26条回答
  •  北海茫月
    2020-11-22 13: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:

    
        
        
        
    
    

    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.

提交回复
热议问题