Is the static safe in Android?

后端 未结 2 1131
故里飘歌
故里飘歌 2021-02-06 07:31

I use a single static class in my code that defines a static field which I\'m reusing between Activity onStop/onStart invocations. Here\'s a scenario:

  1. User clicks
2条回答
  •  别那么骄傲
    2021-02-06 08:23

    If this static data is related to activity which you have just stopped - you could use normal non static fields + onSaveInstanceState method.

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // ... save your Serializable data here in outState bundle
        super.onSaveInstanceState(outState);
    }
    

    The case would be:

    1. you close your activity and go to browser (onStop is invoked)
    2. system kills your application process (onSaveInstanceState is invoked where you save data)
    3. User navigates back to your activity (onCreate is invoked with savedInstanceState parameter)

    In most cases 2nd point will not occure. System can but doesn't have to kill your app process. When it doesn't - you will not get onCreate method but onStart and onResume methods and your fields will be unchanged.

提交回复
热议问题