Prevent Activity Stack from being Restored?

后端 未结 5 558
有刺的猬
有刺的猬 2020-12-02 20:48

When an application\'s process is killed, its activity stack is saved. Then when the application is restarted, all my activities resume and run into null pointers. Rather th

5条回答
  •  爱一瞬间的悲伤
    2020-12-02 21:08

    If you're working with a spalshScreen or whatever LauncherActivity, you can create a Global static boolean and use it like this :

    first find a way to store this static variable (maybe create a Global java file)

    public abstract class Global {
        ...
        public static boolean processKilled = true;
        ...
    }
    

    then, in your laucherActivity (MainActivity or Splashscreen ...) add these lines :

    @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            Global.processKilled = false;
            ...//your code here
        }
    

    In fact, if your app process died it surely wont pass through the code of your launcherActivity. So the static boolean processKilled will remain true. Even if it does, that means your app is currently restarting and processkiled will be correclty set to true and all variables correclty instantiated (No NullPointerException)

    By creating your own restartApp method you'll get what you want :

    (in every activity you have add these lines :)

    @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            if (Global.processKilled){
                restartApp();
            }
            ...//your code here
        }
    

    EDIT

    if you're not a global variable-aholic, you may want to check if savedInstanceState is or isn't null...

提交回复
热议问题