How to access the background location change of Google Maps Android API V2?
•
Android
In my application, I use Google Maps Android API v2. Even if my application is in the background and performs a task, I must obtain the current location coordinates of the location change. How can I do this?
Edit:
This is my tracking location 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)
{
}
}
}
resolvent:
You must create a service that will run even if the application runs in the background. This service must implement or have a locationlistener object
When onlocationchanged is triggered, you can execute the task because it indicates that you have received a new location update
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码