Reputation: 2607
I am trying to develop an app in which I am getting users location updates and when user reaches at some location I am performing some actions. For getting location updates I am using following code.
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
1000,1f,locationListener);
And I am trying to catch location changes in locationlistener's overrided method as follow:
@Override
public void onLocationChanged(Location location) {
Log.e("JK-->>","location updated by gpsping service-->> "+location.getLatitude()+
" "+location.getLongitude());
Toast.makeText(getApplicationContext(),"Location changed!",Toast.LENGTH_SHORT).show();
}
When I tried it on emulator it works fine in foreground and background and also after removing app from recent apps list but problem is that when I try it on real device it's showing toast when my app is open in foreground or background but when I remove my app from recent app it's not showing toast. When I open map from any application (e.g. in googlemap, in my app or in any other app) it's showing toast even if my app is not in recent app list. Hence I can say that my service is running even if my app is killed from recent app but locationmanager can't get location updates.
I have tried to find out solution and I found suggestion to use FusedLocationProviderClient. I have also tried this but it also doesn't work. So, if anyone have solution then please suggest.
Using FusedLocationProviderClient
locationRequest = new LocationRequest()
.setInterval(1000)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setFastestInterval(1000);
LocationCallback locationCallback = new LocationCallback(){
@Override
public void onLocationResult(LocationResult locationResult) {
Log.e("JK-->>","location updated by gpsping service-->> "+locationResult.getLastLocation().getLatitude()+
" "+locationResult.getLastLocation().getLongitude());
Toast.makeText(getApplicationContext(),"Location changed!",Toast.LENGTH_SHORT).show();
}
};
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getApplicationContext());
fusedLocationProviderClient.requestLocationUpdates(locationRequest,locationCallback, Looper.myLooper());
Upvotes: 1
Views: 982
Reputation: 181
Put the location code in sticky service, then start this service as a foreground
.
take a look at this for more information
Upvotes: 1