I am quite new to Android
and I have a scenario while developing an app in Android
which I can't figure out what method I should use to save and access my preferences between different activities, widgets, background services, broadcast receivers and etc ...
I believe there must be a simple built in way for this, but after searching for a while already, I just came across some wired articles which I can't understand at all without pointing out to a simple method to help my situation.
Here is my scenario:
- I have an app which can have multiple activities, multiple widgets, multiple background services and also multiple broadcast receivers (I understand that we use a receiver for a widget as well) ...
- Any of the objects mentioned above might be present or not depending on the current situation, for example a widget can be present in the home screen while no activities or background services are running, or a background service might be running while no activities are running at the moment and this goes on for all other possible situations in the same way ...
- It is also possible that while a widget is present in the home screen, an activity is also running and there might even be a service running as well and some.
- Services might be running on a separate thread.
So based on these conditions what is the standard method used in Android
to achieve my goal of having data saved and accessed between them?
My normal approach is using SharedPreferences
like this:
SharedPreferences p = getSharedPreferences("Settings", MODE_PRIVATE);
But the first problem is that SharedPreferences
needs a Context
and I don't have that in a service for example. Even if I somehow pass my main activity's Context
to the service, what happens when that activity is finished or killed while the same service is still running in a separate thread?
So please if anyone can guide me towards the correct way of saving and accessing data in a such scenario or a way to have an always valid Context
inside services and widgets and etc without any need to an activity being present, so calling for example getSharedPreferences("Settings", MODE_PRIVATE)
from that Context
always returns me same SharedPreferences
object which I can work with the data stored in it from other sources, I would be very happy. Thanks!