How to access location change in background for Google Maps android API v2?

In my application, I use Google Maps android API v2 , and I need to get the current location coordinates when the location changes, even when my application is in the background and performs a specific task. How can i do this?

EDIT:

Here is my location tracking code

LocationService.java

public class LocationService extends Service { String TAG = "LocationService"; LocationManager mylocManager; LocationTracker mylocListener; String myprovider; database obj = new database(this); @Override public IBinder onBind(Intent arg0) { return null; } @Override public void onDestroy() { super.onDestroy(); if(mylocManager!=null) { mylocManager.removeUpdates(mylocListener); } } @Override public int onStartCommand(Intent intent, int flags, int startId) { mylocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); mylocListener = new LocationTracker(); Location loc = null; for(String myprovider:mylocManager.getAllProviders()) { loc = mylocManager.getLastKnownLocation(myprovider); if(loc!=null) { Log.d(TAG,"Updating with last known location"); updateLocation(loc); break; } } if(Build.FINGERPRINT.contains("generic")) { Log.d(TAG,"App running on emulator"); mylocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mylocListener); } else if(mylocManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { Log.d(TAG,"GPS Provider available"); mylocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mylocListener); } else if(mylocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { Log.d(TAG,"NETWORK Provider available"); mylocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mylocListener); } else { Log.w(TAG,"No provider found. Stopping service"); stopSelf(); } return super.onStartCommand(intent, flags, startId); } public class LocationTracker implements LocationListener { @Override public void onLocationChanged(Location loc) { Log.d(TAG,"Updating exact coordinates"); Toast.makeText(getApplicationContext(), "Location changed", Toast.LENGTH_SHORT).show(); updateLocation(loc); stopSelf(); } @Override public void onProviderDisabled(String arg0) { stopSelf(); } @Override public void onProviderEnabled(String arg0) { } @Override public void onStatusChanged(String arg0, int arg1, Bundle arg2) { } } } 
+4
source share
1 answer

You will need to create a Service that will be launched, even if the application is in the background. This Service must implement or have a LocationListener object.

When onLocationChanged triggered onLocationChanged you can complete your task, as this means that you received a new location update.

+3
source

All Articles