开发者

Static variables in Android and low memory - a few questions

In my app, I use a static variable to hold the current user id. There is a bug that is very hard to reproduce of this user id simply disappearing. While it could be related to a bug in how this variable is set during application loading (I still wasn't able to reliably reproduce this situation in a controlled environment, so I'm not really s开发者_运维知识库ure exactly what happens), I'm starting to think this is related to how memory gets reclaimed from static variables (something I didn't consider before).

So, when can my static variable simply disappear?

  • As far as I understand, static memory can get reclaimed if the OS reports low memory - can it happen while the app is in the foreground? Or only background?
  • Are there any possible ways static memory is getting reclaimed without a low memory condition? I think sometimes the variable disappears without the app even going to the background and I'm not sure any low memory events occur (AFAIK low memory refers to the whole OS, not the app's memory)
  • What is a good way to simulate static variables getting reclaimed by the OS to see how the application behaves and subsequently fix the bugs?

Anything adding more clarity to my understanding will be appreciated.

Thank you.


This is question super, super old, but I was writing a blog post and mentioned seeing this. I have no idea if you're still working on this app (doubtful), or if you're still seeing this issue (also doubtful). My guess is you set these statics in the Activity that your app launches with. Of course, if your app gets shut down, then restarted, you won't go through that activity.

Lazy loading statics, or initializing them in a custom Application object generally takes care of this.

I've done a fair amount of research on the "statics removed in low memory" idea, and the basic answer is it doesn't happen. Ever.


I suggest you are not using static variable to hold the current user ID as the static variable is not one of the best way to store your data (I assume userID as a data which will remain on every session of your app, except when the user is logout).

The simplest way is to go with Shared Preferences. Look at the Android Data Storage to read the best (practice) way to store your data in Android.

From your need, I guest you should go on with SharedPreferences. No more problem and you don't even need to simulate any variables reclaimed by the OS.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜