java - 防止类卸载,java
问题描述
在我的 Android 应用程序中,我有一个静态类来在整个应用程序中共享一些变量和函数。
此类中的一些变量在其他活动中启动(例如,一旦用户从网格视图中选择某些内容,然后我将其选择存储在此静态类中,以便稍后在另一个活动中使用它)
一切都很好,但看起来在应用程序一段时间不活动之后(一旦它停留在后台),这个静态类被销毁,然后用默认值重新初始化,假设是“错误的”。
或者,可能整个应用程序都被卸载了,在我回调它之后,它恢复了最后一个试图访问某些变量但它们被重新启动的活动
有什么方法可以防止类重新初始化或保留静态值或以其他方式保留这些值并在重新创建活动后恢复它们?..
非常感谢!
解决方案
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.
推荐阅读
- laravel - Laravel 5 - Pre-Populate form using 'old'
- c - How is this basic algorithm O(n)?
- java - 程序导致堆栈溢出
- c# - Is there a simpler way to query from MySQL in ASP.NET MVC?
- swift - 如何在 swift 中使用 int 标头发出 http 请求
- python-3.x - 学习使用 python 在亚马逊上抓取产品详细信息
- mysql - 提高文本列的搜索速度
- javascript - 有没有办法确定什么 javascript 对 DOM 元素进行了非常具体的更改
- php - 在 PHP 中访问 JSON 数组数据
- sql-server - 在返回查询中不尊重 upsert 子句的 Sequelize where 子句