Bertuz
Bertuz

Reputation: 2566

background service with data for later use best practice

I'm writing an application that needs to register the actual location every minute, whether it's in foreground or background. When the user decides it's time to stop tracking, I want to gather all the data collected and use them.

To do that, I've thought about an architecture that tries to save the battery and it tries to be as efficient as possible. I'm wondering if my choice is decent enough. Here it is:

  1. I start a service S from an Activity through startService(). The service will construct a data structure to save data for later use. A communication between the activity and the service will also be created through Messenger objects.

  2. I register to location updates that will be managed by a receiver R. It will be something like this:

    this.lm= (LocationManager) getSystemService(LOCATION_SERVICE);        
    Intent locationIntent= new Intent(getApplicationContext(),TravelPosition.class);
    PendingIntent locationPendingIntent= PendingIntent.getBroadcast(getApplicationContext(), 0, locationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 7000, 1, locationPendingIntent);
    
  3. Each time the receiver R is triggered, it will communicate with the service S. I was thinking about a startService(Intent) where I put the coordinates in the Intent's extras.

  4. The service S will store the new data (my new location coordinates and other infos that I generate with them) in its inner data structure. Everything should work whether the app is running in foreground or background

  5. Once the user stops the tracking by means of a button in the activity, the latter will communicate with the service to get the data stored until then, then it calls stopService

what do you think about this? One more extra question: If a user wants to kill the app, what happens to the receiver? Will it open the app back?

Upvotes: 2

Views: 2136

Answers (1)

Victor Ronin
Victor Ronin

Reputation: 23268

First of all, you are right thinking architecture through before start writing a code :)

Second, I recommend to read following links:

http://developer.android.com/guide/topics/location/strategies.html http://devdiscoveries.wordpress.com/2010/02/04/android-use-location-services/

Third, In your case, you don't need a service S. You can register receiver R and do everything you need in this receiver R (including processing and saving data). In the case, if you exit from your application, you will still continue to receive location updates.

Upvotes: 2

Related Questions