3
votes

I have a BroadcastReceiver that has to get and modify some data from the application class. This data is retrieved and modified in some activities too.

I read this post:

getApplication() vs. getApplicationContext()

And, as it says, getApplication doesn't always return the same object as getApplicationContext. In my case, if I set an integer in my BroadcastReceiver using getApplicationContext and then I check its value in my activity (using getApplication) it's always 0 (default value).

I tried using getApplicationContext in both places, but the objects returned aren't the same. Is there any way to get the same object in BroadcastReceiver as I get in my activity using getApplication? Should I use SharedPreferences instead?

Here's an example:

BroadcastReceiver:

MyApp app = (MyApp)context.getApplicationContext();
app.setNumPA(10);

Activity:

MyApp app = (MyApp) getApplication();
Log.d("MyActivity", "Num PA: "+app.getNumPA());

In my activity the log always shows "Num PA: 0".

1

1 Answers

4
votes

You should definately use some persistent storage, for example SharedPreferences.

A reason behind this - your application instance can be killed by Android OS almost at any time (while your app in background). So, you can't rely on your variables, even static. You should save your state in persistent storage instead.