requestLocationUpdates vs getLastLocation - java

Does calling requestLocationUpdates from LocationManager update the location returned by getLastLocation?
ie, can i do this:
call getLastLocation. it returns null, then:
call requestLocationUpdates;
receive onLocationChanged on my listener, and do nothing
And after that, call getLastLocation and get something !=null?
Thanks!

getLastLocation will return the last location if LocationManager has a previous location reading. If LocationManager doesn't have a previous location then null will be returned.
requestLocationUpdates will request ongoing location updates until you unsubscribe from location updates.
Further details can be found here:
https://developer.android.com/training/location/retrieve-current.html
The following explanation is given on why getLastLocation might return null:
Location is turned off in the device settings. The result could be null even if the last location was previously retrieved because disabling location also clears the cache.
The device never recorded its location, which could be the case of a new device or a device that has been restored to factory settings.
Google Play services on the device has restarted, and there is no active Fused Location Provider client that has requested location after the services restarted. To avoid this situation you can create a new client and request location updates yourself. For more information, see Receiving Location Updates.

Related

OnLocationResult of fused Location api is only called once even when i have requested updates in given time interval in android

I have read a few questions and answers related to this , but none has solved my problem. Please suggest me what should i do. I am using this fused location api in my android background service. And i have provided all the nougat/marshmellow checks also. But i get result location only once or first time, after that , the onLocation result is not called, is it so that only when i change my location it will be called ? please help
heres my simple onCreate of service:
#Override
public void onCreate() {
super.onCreate();
fusedLocationProviderClient= LocationServices.getFusedLocationProviderClient(this);
locationRequest=new LocationRequest();
locationRequest.setInterval(4000);
locationRequest.setFastestInterval(4000);
locationCallback=new LocationCallback(){
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
Log.i("serviceTag","onLocationResult called");
}
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED){
fusedLocationProviderClient.requestLocationUpdates(locationRequest,locationCallback, Looper.myLooper());
}
}
FusedLocationProviderClient provides location updates only in foregrounded state either when an Activity (any not necessarily the one requesting or using location updates) is resumed or when a foreground service associated with location foregroundServiceType is started.
From Android 10, framework developers most likely choose to sub categorize foreground services by a type to ensure not all apps with generic foreground services like media apps gets free access to locations when backgrounded. Given that, it is trivial for application developers to just add this “location” type in manifest for unrelated foreground service to work around the limitation.
https://medium.com/#debuggingisfun/android-foregroundservicetype-8857a36f36b9

Retrieving geo location in my app is far less accurate than what Google Maps app shows in the same time on my device

In my app, I've tried two ways of accessing location:
a) Using LocationManager and GPS_PROVIDER. I accept location to be processed if it has accuracy 50 or less. App receives location however most of the time receives no location at all - while Google Maps when I start it to try it out gets my location constantly and more precise than my app.
Here are parts of the source related to this:
Start to listen to locations:
// in service class, function to start listening for locations.
// class implements android.location.LocationListener interface
this.locman = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
if( !this.locman.isProviderEnabled(LocationManager.GPS_PROVIDER) ){
Log.d("","GPS is not enabled");
}else{
this.locman.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
this.onLocationChanged( this.locman.getLastKnownLocation(LocationManager.GPS_PROVIDER) );
}
android.location.LocationListener implementation of onLocationChanged function:
#Override
public void onLocationChanged(Location location)
{
... showing provided Location on the map
}
in manifest file:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
This can give me relatively frequent updates, but sometimes has huge gaps. I believe maybe it's problem with connecting with enough satellites, however if I open Google Maps in the same time - it works flawlessly. No time gaps between location updates, and more precise than what I am getting here.
I thought it may be needed to use LocationClient and LocationRequest instead, counting that maybe Google Play API may have some internal interpolation / prediction / whatever that improves precision.
b) Using GooglePlay API with LocationClient and LocationRequest. I've installed Google Play SDK, and also tried Google's sample apps. Here is my code related to this:
// in service class, function to start listening for locations.
// class implements com.google.android.gms.location.LocationListener,
// com.google.android.gms.common.ConnectionResult.OnConnectionFailedListener and
// com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks interface
this.locclient = new LocationClient(this.getApplicationContext(),this,this);
this.locclient.connect();
implementation of onConnected:
#Override
public void onConnected(Bundle dataBundle)
{
LocationRequest req = LocationRequest.create();
req.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
req.setInterval(2000); // 2 sec
req.setFastestInterval(16); // 60 fps
this.locclient.requestLocationUpdates(req, this);
}
And of course onConnectionFailed and onDisconnected is implemented and breakpointed - never gets in, while onConnected is called.
Implementation of com.google.android.gms.location.LocationListener:
#Override
public void onLocationChanged(Location location)
{
... showing provided Location on the map
}
In this case, I get updates immediately, however off for like 200m or more.
In desperation, I tried MyLocation app that is on Google Play and it shows SAME OFFSET!
When I try Google Maps, in the same time, it shows absolute accuracy like 5-6m the most.
Important notice: I am located in Shanghai, China. Not sure if this is related in any way.
How is it possible to have such huge offset between Google Maps and Google's own example of location service (MyLocationDemoActivity.java, provided in google_play_services/samples/maps/)?? To clarify: Google's map demo provided with Google Play Services sample codes, also shows SAME OFFSET (~200m) away from my real location, while in the same time Google Maps app shows precise location.
I'm using Nexus 4 as development platform.
Compiler is ADT (Eclipse). All up-to-date.
Really hope for some quick breakthrough from anyone here!!! Thanks in advance!
P.S.
I have now tried to use LocationRequest.PRIORITY_NO_POWER as setting for location request, to have my app get location update only when another app requested it. I've then started Google Maps, and switched back to my app. It immediately received location. I've copied long/lat into http://maps.googleapis.com/maps/api/staticmap?center=31.229179,121.422615&zoom=16&format=png&sensor=false&size=640x640&maptype=roadmap to test it out, and it is showing SAME OFFSET. While Google Maps on my phone shows exact location.
Is it possible that maps from Google have offset? Or that there is an offset to long/lat received?
I don't have enough reputation to comment yet so I'm writing an answer.
This is most likely related to the China GPS offset problem. The Chinese government insists on not allowing users to record accurate GPS data in some scenarios ("national security something blah blah") and force companies like Apple/Google to abide by the local laws.
Here is a link with some good information on the topic:
http://www.sinosplice.com/life/archives/2013/07/16/a-more-complete-ios-solution-to-the-china-gps-offset-problem
As in above answer, offset is because of China government regulation. However people managed to get transform used at least by GoogleMaps and HEREMaps. It is here written in C#.
Using that you can convert real coordinates to transformed ones with maximum 20 meters error. There are also more accurate implementations.
If you don't want to modify your software, you can use something based on this. It is my simple Xposed module to convert coordinates for all applications using LocationManager.

Android GPS does not work until restart on new phones

I have posted about this issue before, and found a few other people who have had the same issue with no solutions found.
I am developing an Android app that submits a JSON query to a server with the obtained GPS coordinates and geocoded Zip Code. For brand new users that have never downloaded the app, GPS does not work whatsoever. It is not until rebooting the phone that GPS will work. After installing the app and then rebooting, the GPS will work every time without problem, even if they restart again.
There is precious little information on this issue, and the only issue I have found refers to using Google Play Location Services, with no further details. Has anyone else had this issue? My development is completely halted until this issue can be resolved.
EDIT:
Here is the link to the MainActivity.java file that calls the geopositioning functions.
Here is the link to the MyLocation.java file that contains the actual logic for multiple sources of geolocation
I have no doubt that there are much better ways of doing GPS. I'm very new to Android development, so any help on this front is very much appreciated.
EDIT 2:
I have wiped my phone with a factory reset, and started from scratch. I still cannot replicate the issue on this device, only on phones using the app for the very first time prior to a restart.
Looks like you're registering both the GPS and NETWORK providers to listen for a location for 10 seconds, and when the timer goes off after 10 seconds you try to get the most recent location from both providers.
There are a few things going on here.
First, you seem to be listening for updates in the wrong method. Your two listeners should look like:
LocationListener locationListenerGps = new LocationListener() {
// This will never be called, its not part of the LocationListener interface - http://developer.android.com/reference/android/location/LocationListener.html
/* public void onStatusChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
} */
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
public void onLocationChanged(Location location) {
// This is the correct method to receive location callbacks
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
Second, I'd use the ScheduledThreadPoolExecutor or Handler instead of Timer.
From the Timer docs:
Prefer ScheduledThreadPoolExecutor for new code...This class does not offer guarantees about the real-time nature of task scheduling.
If a reboot is required to get the app working, its likely something to do with the Timer not firing after 10 seconds. Note that this doesn't necessarily mean that GPS itself isn't working.
Handler should do the job and it's designed for Android, so I'd suggest using it. It looks like:
Handler handler = new Handler();
handler.postDelayed(getLastLocation, 10000);
...and your GetLastLocation would change to:
Runnable getLastLocation = new Runnable() {
#Override
public void run() {
...
}
}
...and your cancel() and other methods would need to reference the Handler.
Also, note that you're declaring the Location object in your MainActivity with a provider type of NETWORK_PROVIDER, and then setting the lat/long in that object.
public Location mUserCoordinates = new Location(LocationManager.NETWORK_PROVIDER);
So, the location type in MainActivity will always appear to be of NETWORK_PROVIDER, no matter the actual source.
Also, doesn't look like your MainActivity needs to implement LocationListener, as its never registered with the LocationManager.
Finally, instead of using two listeners for GPS and NETWORK, I would suggest using the Fused location provider in Google Play Services, as discussed here:
http://developer.android.com/training/location/receive-location-updates.html
You'll be limited to devices Android 2.2 and up with Google Play Services installed, but in my opinion its worth it to avoid dealing with some of the eccentricities of location in the platform and managing more than one provider. For more about Fused location provider and how it differs from listening directly to GPS and NETWORK providers, see this 2013 Google I/O presentation - Beyond the Blue Dot: New Features in Android Location
Why do you use Google Play Services Location API?
The only new feature provided by Play Services is Geofencing. From your answer i assume that you don't want to use Geofencing but just "usual" location requests.
The Android platform provides a great API for such requests which does not requires Google Play Services. I never had the problem you described when using it.
Note that although Google claims the Play Services to be better than the Android API, this is not true since API 9 (Android 2.3), as long as you use the newer LocationManager.requestLocationUpdates methodes that don't require a provider to be specified.
See: http://developer.android.com/guide/topics/location/strategies.html
I had the same issue with the regular Location API earlier. I swiched to Play Services, and it seemed to work. Lately sometimes I experience this issue again with Google Play Services. It is really strange, and based on my experience the probelem is system-wide, so when my app couldn't find location, than the Google Maps app couldn't eather. Note that I use Cyanogenmod, so it can be some bug within it.

Android GPS update location

I am making simple application which based on phone's location. I am using this code for GPS location. In the main() function I am requesting the GPS location and then I am working with it. (I am calculating the sunrise and sunset)
I can get the location, but when I start the application I get the LastKnown location. So, if I want real "new one" location I must wait for GPS lock on and then restart the application.
So, my question is: How can I get a "fresh" location?
Ok. I have an idea.
Can I call MainActivity refresh from another class?
in GPS class I have this
private final Context mContext;
#Override
public void onLocationChanged(Location location) {
startActivity(new Intent(mContext, MainActivity.class));
}
But this doesn't work. Can anyone help?
Here is the overview of location services in Android. Here is the LocationManager class at the heart of location services in Android.
Here is an Android developer tutorial on "Location Strategies". Here is another tutorial that might be usable.
Also, you cannot just ask Android for your current position, since GPS may take quite some time to get a fix. Instead, you need to request location updates and use the first update you get, or similar patterns.

requestSingleUpdate(...) doesn't automatically fetch GPS location

If we want to get a single GPS fix in Android we actually use the known function requestSingleUpdate() with LocationManager.GPS_PROVIDER, right?
Now i was exactly doing this in my function getLocation() with GPS turned on, but the device is not automatically going to establish a connection, unless i manually turn off the GPS and then turn it on again. requestSingleUpdate() for the network provider works flawlessly, i just don't know why this doesn't go for the GPS fixing.
Here is a part from my source code:
getLocation() is run by another object with a timer every 2 minutes.. in getLocation() if the GPS and Network are on, it tries to get a GPS fix in the first minute and then it fetches the network location if there is no GPS fix available.
public boolean getLocation() {
// DEBUG
Log.d("GPS Connection", "Entering getLocation()");
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!gpsEnabled && !networkEnabled)
return false;
if(gpsEnabled && networkEnabled) {
// DEBUG
Log.d("GPS Connection", "Request GPS Data");
locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, gpsLocationListener, Looper.getMainLooper());
gpsGetLocationTimeout = new Timer();
gpsGetLocationTimeout.schedule(new GetNetworkLocation(), GPS_MAX_CONNECTION_TIME_MS);
}
...
From the Android documentation:
It may take a while to receive the most recent location. If an
immediate location is required, applications may use the
getLastKnownLocation(String) method. In case the provider is disabled
by the user, the update will not be received, and the
onProviderDisabled(String) method will be called. As soon as the
provider is enabled again, the onProviderEnabled(String) method will
be called and location updates will start again.
GPS can take a long time to get from a cold start. You may never get a GPS if you are indoors, in a parking structure, surrounded by tall buildings, have a crappy phone, or if the GPS Satellite Gods are in a funny mood.
In some applications, we will do something like request a GPS location, then if it hasn't arrived after 60 seconds, cancel the request so that we don't kill the phone's battery with a GPS RX left on semi-permanently.
You can request last known location and check its age and decide if it is recent enough to use. Network location is fast and cheap (in terms of battery use) and a good strategy is to use network location until you get GPS.
My experience coding GPS in Android is that the GPS is going to do what it wants to do which is in many ways not what the documentation leads you to expect. GPS needs to be treated as something which may or may not be available and the logic of your program can be designed to handle that.

Categories

Resources