0

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.

1 Answers1

0

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?

Community
  • 1
  • 1
hatcyl
  • 2,190
  • 2
  • 21
  • 24
  • Thanks for answering, hatcyl. Now the thing is if I kill the process where my application is running, every variable, including shared preferences, die. So, where can I increase the counter I need to later refresh it on the user's screen? – user1513548 Jul 10 '12 at 14:06
  • I solved it reading the link you shared and also the documentation. Thank you. – user1513548 Jul 10 '12 at 17:52