Search code examples
androidservicesharedpreferencesandroid-contentprovider

Android: change variables (counters) of a closed application using a service


stackoverflow community.

I have a problem that I've been trying to solve since a few days ago.

I have a service running in an Android application that receives and sends messages. For those messages, I have counters that save the ammount of sent and received sms and errors. For example, when a message is sent, the counter adds +1 and shows the total on screen (in a not focusable editview).

Another thing I do is bind my service, so I can switch it on or off according to my needs. Everything works fine when the application is running, but if it is finished my variables are lost, but I need to keep counting the messages somehow and show the values when the user opens the application again. How can I do this?

I've been using shared preferences variables to save these numbers and others configurations, but when the app is killed, those numbers can't keep increasing.

When the application is closed, can I save the counters values somewhere? Can I access to the shared preferences from the service with the application closed? What if I use a content provider? Can I access to it from the running service even if the app is closed?

Regards.


Solution

  • There is no problem accessing shared preferences from a service. So, just save your variables on your services onDestroy() method and reload them onCreate();

    This should work to get the preferences:

    Context ctx = getApplicationContext();
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
    

    Here's a great answer: How do I get the SharedPreferences from a PreferenceActivity in Android?