Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BroadcastReceiver Life Cycle -- Static Variables

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.

like image 599
Sush Avatar asked Jun 09 '11 21:06

Sush


People also ask

What is the life cycle of BroadcastReceiver?

A BroadcastReciever life cycle ends (ie stop receiving broadcast) when you unregister it. usually you would do this in the onPause/onStop method.

What is static and dynamic broadcast receiver?

And that was all about creating broadcast receivers statically. The main difference in working between the static and dynamic receivers is that the static receivers will run if the application is running/not running. But the dynamic receivers will run if the application is running.

Why are dynamic register more popular than static register?

Static mostly used when you want to listen to an event all the time & dynamic may be used when one of the screen of your application is open and unregister that receiver once app is closed.

What is the role of the onReceive () method in the BroadcastReceiver?

onReceive. This method is called when the BroadcastReceiver is receiving an Intent broadcast. During this time you can use the other methods on BroadcastReceiver to view/modify the current result values.


2 Answers

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

like image 116
Squonk Avatar answered Oct 22 '22 16:10

Squonk


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

like image 22
Will Kru Avatar answered Oct 22 '22 17:10

Will Kru