BroadcastReceiver 生命周期——静态变量
我有一个 BroadcastReceiver 类。我声明了一些静态变量,其值在 onReceive() 方法中更新。据我所知,静态变量将在 onReceive 调用中保持其值。当我丢失这些值时是否有可能(比如我的类将被卸载并重置静态变量)?这些基本上是我需要可用于多个 onReceive 调用的一些临时变量。
I have a BroadcastReceiver class. I have some static variables declared whose value is updated in side the onReceive() method. As per my knowledge static variable will keep it's value across the onReceive calls. Is there any possibility when I will loose those values(Like my class will be unloaded resetting the static variables)? These are basically some temporary variables I need to be available for multiple onReceive calls.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从 BroadcastReceiver 生命周期 的文档中...
从系统会快速清理事物的意义上来说,这不会使静态变量的使用变得实用。我会尝试通过调用...
context.getSharedPreferences("MyReceiver", MODE_PRIVATE)
...在接收器的
onReceive(...)中 使用
方法(将SharedPreferences
"MyReceiver"
替换为对您的应用有意义的名称)。From the documentation for BroadcastReceiver Lifecycle...
This isn't going to make the use of static variables practical in the sense that things will be cleaned up quickly by the system. I'd try using
SharedPreferences
by calling...context.getSharedPreferences("MyReceiver", MODE_PRIVATE)
...in the receiver's
onReceive(...)
method (replace"MyReceiver"
with some name which makes sense to your app).或者您当然可以在活动类中声明静态变量。
Or you could of course declare the static vars within your activity class.