BroadcastReceiver生命周期 - 静态变量 [英] BroadcastReceiver Life Cycle -- Static Variables

查看:259
本文介绍了BroadcastReceiver生命周期 - 静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个BroadcastReceiver类。我有一些声明它的值在onReceive()方法中更新的静态变量。根据我的知识,静态变量将保持onReceive调用的值。有没有可能,当我将失去这些价值(像我的班将被卸载重置静态变量)?这些基本上是我需要用于多个onReceive调用的临时变量。

解决方案

从文档 BroadcastReceiver生命周期 ...



< blockquote>

BroadcastReceiver对象仅在调用onReceive(Context,Intent)期间有效。一旦你的代码从这个函数返回,系统会认为这个对象已经完成并且不再有效。

这不会使系统使用静态变量是很实际的,因为系统会快速清理事物。我试着用 SharedPreferences 调用...



context.getSharedPreferences( MyReceiver,MODE_PRIVATE)



...在接收者的 onReceive(...)方法(将MyReceiver替换为一些对您的应用有意义的名称)。


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.

解决方案

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

这篇关于BroadcastReceiver生命周期 - 静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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