0

I´ve an Android Application that holds some static objects on an class that extends Application class, using the same approach as exemplified here.

The objects that is hold by this class is shared and manipulated between all activities on my app.

Everything works well, but, some time ago, I noticed that when the application runs on backgroud for some time, when it´s restored, the data that was stored on the extended class has gone, and the app starts to throws a lot of NullReference exceptions.

I think that this happens because of the application was being temporary destroyed by the OS, to be recreated when we need to use it again.

So, how could I handle this scenario? Is there any way to discover that the application is being temporary destroyed, without subscribing to the onDestroy event of an Activity? On a test that I did, the onDestroy event was not called when I asked the background process of my app to being stopped.

Thanks a lot!

4

2 回答 2

0

无法确定进程何时会被终止,因此您始终应该将重要数据存储在某个地方(例如 sd 卡)并在 App 类的 onCreate() 方法中恢复它。

还要看看 onLowMemory() 和 onTrimMemory(),释放内存中所有不必要的数据以帮助操作系统防止破坏您的应用程序,导致确定您的应用程序的原因之一是内存不足。

于 2012-07-02T04:57:31.533 回答
0

不,没有办法知道何时需要持久化存储在静态变量中的数据。至少据我所知,系统不会通知您有关此问题的回调。

所以你应该只使用静态变量来存储临时数据,或者缓存从永久源访问的数据。我在许多项目中都遇到过这个问题,而且我总是最终使用意图/共享首选项/sqlite 等来可靠地跨活动存储数据。

于 2012-07-02T05:00:53.077 回答