在 Android Studio 中丢失对静态数据的引用 [英] Losing reference to static data in Android Studio

查看:60
本文介绍了在 Android Studio 中丢失对静态数据的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我的应用程序进入后台时,我遇到了静态数据丢失实例的问题,导致空指针异常错误.

I'm having issues with instances of static data being lost when my app goes into the background, causing null pointer exception errors.

静态数据非常依赖于上下文或状态",并且不能在初始化时一般生成.

The static data is very context or 'state' dependant, and can't be generated generically on initialisation.

为了确保我保留这些数据,我是否会强制将数据写入存储,或者有其他方法可以确保当应用程序进入后台时我的静态数据不会丢失?

To ensure I keep hold of this data, will I be force to write the data to storage or this there some other way of ensuring my static data isn't lost when the app is put into the background?

推荐答案

静态字段是类的一部分,而不是对象.当 Android 回收内存时,静态字段也将被回收,您将丢失其中保存的所有数据.请记住,操作系统可以随时为您的应用程序在后台回收内存.

Static fields are part of the class, not an object. When Android recycles memory, the static fields will be recycled as well and you will lose all data held in them. Remember that the OS can, at any point, reclaim memory for your application when it's in the background.

如果您有想要保留的状态,则需要将其持久化到磁盘,在 Android 上,依赖于后台内存中的任何内容是一种冒险的策略.

If you have state that you wish to preserve, you will need to persist it to disk, on Android, relying on anything that's kept in memory in the background is a risky strategy.

我会为此使用共享首选项,但如果您愿意,也可以使用序列化文件流.共享首选项更简单,而且文档齐全.

I'd use shared preferences for this, but you could also use a serialized file stream if you wanted to. Shared preferences are just easier and well-documented.

在您的 onResume() 方法中,您会读回这些值,并且您当然会将它们保存在 onPause() 中.这还可以让您处理一些情况,例如有电话打进来或用户切换到不同的应用程序,即使只是片刻.

In your onResume() methods, you'd read back the values and you'd of course persist them in onPause(). This will also allow you to handle situations where, for example, a phone call comes in or where the user switches to a different app, even for just a moment.

这篇关于在 Android Studio 中丢失对静态数据的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆