Is the static safe in Android?

2019-03-16 14:27发布

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 on "Authorize" button (static data is initialized)
  2. Activity is stopped and web browser is called
  3. Browser executes callback and Activity is restored (static data is reused)

At least one of my users reports the failure at step 3 which I cannot reproduce but which looks like reset of static data

Any suggestions?

2条回答
贼婆χ
2楼-- · 2019-03-16 15:07

That is not safe. Your process can be killed between onStop and onStart, so all static data will be gone. In fact your activity can even be killed before it gets to onStop. In your tests the process was not killed, but it was for the user. See the Android activity life cycle which has a nice flow chart showing the possibilities.

You need to store the data some other way, in prefs or database for example.

查看更多
▲ chillily
3楼-- · 2019-03-16 15:19

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.

查看更多
登录 后发表回答