BroadcastReceiver 生命周期——静态变量

发布于 2024-11-14 21:51:15 字数 162 浏览 5 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

街角卖回忆 2024-11-21 21:51:15

BroadcastReceiver 生命周期 的文档中...

BroadcastReceiver 对象仅在调用 onReceive(Context, Intent) 期间有效。一旦您的代码从此函数返回,系统就会认为该对象已完成并且不再处于活动状态。

从系统会快速清理事物的意义上来说,这不会使静态变量的使用变得实用。我会尝试通过调用...

context.getSharedPreferences("MyReceiver", MODE_PRIVATE)

...在接收器的onReceive(...)中 使用SharedPreferences 方法(将 "MyReceiver" 替换为对您的应用有意义的名称)。

From the documentation for BroadcastReceiver Lifecycle...

A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent). Once your code returns from this function, the system considers the object to be finished and no longer active.

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).

就此别过 2024-11-21 21:51:15

或者您当然可以在活动类中声明静态变量。

Or you could of course declare the static vars within your activity class.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文