Can I detect if Android has killed the application (task process) from a Notification Intent / PendingIntent?

会有一股神秘感。 提交于 2019-11-28 07:06:28

The easiest way to determine if Android has killed the process and then created a new process is as follows:

In your root Activity (the one with ACTION=MAIN and CATEGORY=DEFAULT) create a public static boolean variable like this:

public static boolean initialized;

in onCreate() of your root Activity, set this variable to true.

In onCreate() of all your other activities, you can check if Android has killed/recreated the task by checking the state of the boolean, and if the app hasn't been initialized, you can redirect to the root Activity or call an initialization method or whatever... like this:

if (!RootActivity.initialized) {
    // Android has killed and recreated the process and launched this
    //  Activity. We need to reinitialize everything now
    ... redirect to root activity or call reinitialize method
}
colens

Since the process id will change when app is being killed and restarted, you can use this to check it:

In onSaveInstanceState(Bundle outState) get current process id and save it in outState:

onSavedInstanceState(Bundle outState){
   super.onSaveInstanceState(outState);
   outState.putInt("my_pid", Process.myPid());
}

Then in onCreate(Bunde savedInstanceState) compare the saved process id and the current process id:

onCreate(Bundle savedInstanceState){
   if(savedInstanceState!=null){            
      if(savedInstanceState.getInt("my_pid",-1)==android.os.Process.myPid())
         // app was not killed    
      else
        // app was killed
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!