How do I programmatically “restart” an Android app?

后端 未结 26 2013
小鲜肉
小鲜肉 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:07

    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 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.

提交回复
热议问题