Question

I'm working on an app, which is using a homescreen widget to play a sound from a source, that the user chose in the app's main activity. After some time my app looses the information about the assigned sourcefile and I have to re-enter the main activity to pick a sound again. I guess this happens because my app is killed or put asleep by the OS.

So my question is how to make those settings I've made in the main activity persistent, so that my homescreen widget doesn't stop to work after a certain amount of time.

Also I'd like to know if there is a need, to keep this main activity alive somehow, since the homescreen widget is sending broadcasts to it when the button is pressed in order make it send a message to my mediaplayer service, which would play the sound.

Was it helpful?

Solution

You need to use SharedPreferences.

//Set the shared preferences
SharedPreferences prefs = getSharedPreferences("myPrefs", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("myString", "myValue");

//Get the shared preferences
string myString = prefs.getString("myString");

Regarding the second part of your question, you would likely need to run a background service that the broadcast receiver and the activity can use.

The activity shouldn't be controlled from the widget and instead the activity GUI and the Widget control accesses methods within the background service to control the media player service.

I don't know too much about media player services or background tasks so maybe someone has a better method but hopefully will get you started.

Some information about services on android can be found at http://developer.android.com/reference/android/app/Service.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top