Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtain application from ReceiverRestrictedContext as if getApplication was used (not getApplicationContext)

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

like image 402
PX Developer Avatar asked Dec 05 '25 14:12

PX Developer


1 Answers

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.

like image 113
HitOdessit Avatar answered Dec 08 '25 04:12

HitOdessit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!