首页 > 解决方案 > 防止类卸载,java

问题描述

在我的 Android 应用程序中,我有一个静态类来在整个应用程序中共享一些变量和函数。

此类中的一些变量在其他活动中启动(例如,一旦用户从网格视图中选择某些内容,然后我将其选择存储在此静态类中,以便稍后在另一个活动中使用它)

一切都很好,但看起来在应用程序一段时间不活动之后(一旦它停留在后台),这个静态类被销毁,然后用默认值重新初始化,假设是“错误的”。

或者,可能整个应用程序都被卸载了,在我回调它之后,它恢复了最后一个试图访问某些变量但它们被重新启动的活动

有什么方法可以防止类重新初始化或保留静态值或以其他方式保留这些值并在重新创建活动后恢复它们?..

非常感谢!

标签: javaandroidvariables

解决方案


Instead of looking for ways (or rather hacks) to stop re-initialisation of your classes or storing the variables in a static class I would rather suggest you to store the state of your app in local storages like Shared Preferences or the SQLite DB.

The advantage of this would be you can access this variables in any part of your app and secondly you will get rid of those static classes and variables which are the main culprit of Memory leaks and ANRs.


推荐阅读