Forum Xamarin.Android

Announcement:

The Xamarin Forums have officially moved to the new Microsoft Q&A experience. Microsoft Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

To create new threads and ask questions head over to Microsoft Q&A for .NET and get involved today.

Preserving data in android service

Hi. I am new to Xamarin android - actualy to android in general so I hope my question is not to trivial. I am working on a sample application - just to try out the platform. My application is very basic. When started, it's start-up activity starts a service and then binds to it. The service(which extends an IntentService) calls a REST based service on the server to retrieve some data and it registers the app. with the GCM(google cloud messaging) in order to receive notifications when the data on the server is changed. Initialy I thought that android services are more like windows services but I soon found out that as soon my Activity un-binds the service(when the activity is paused) the service is destroyed. And there lies my problem. When the activity is resumed and it re-starts the service the data which the service retrieved from the server is gone. Storing the data to database or a file seems like overkill since I only need to store it while the app. is running. I know I can store the data to some static field in the service or somewhere else but that seems very wrong to me. I also thought about storing the data in the activity but that would cause problems in the future if I decided to add other activities to the app which would work with the same data. So what is a good solution to my problem? Any advice will be appreciated.

Uros

Posts

  • UroBregarUroBregar USMember

    I think I found the answer to my question. So I am publishing the answer if somebody else will encounter the same problem. After reading some chapters in a book and a few online articles I think there is no other way than to store the values. So where to store it? Basicaly what ever mechanism(Shared preferences, file, SQLite) you chose you end up writing to a file. Which one you should choose I think it depends on the data you have to store. Key-value pairs can be stored to SharedPreferences for more complex data you can choose the SQLite database.
    Uros

  • cfraz89cfraz89 USMember

    Hey Uro,

    I believe this is what the OnSaveInstanceState (Bundle state) function within an activity is for. You can pack all the data you want to save into the bundle, and then when your activity is recreated in OnCreate (Bundle savedInstanceState) you unpack everything from the bundle again.

    Chris

Sign In or Register to comment.