I am using LocationManager to get the last known location. I found out that it returns null unless the GPS is turned on.
here is my code
mLocationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
List<String> providers = mLocationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
#SuppressLint("MissingPermission") Location l = mLocationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
is there any way to get last known location without needing to turn GPS on?
Related
After I disable location services on my phone and then enable them getLastKnownLocation() returns null although the provider it used is enabled.
Does anyone know how to solve this problem?
Also, if I open Google maps app and then return to my app it seems to solve the problem.
Code:
private Location getLastKnownLocation() {
LocationManager mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
List<String> providers = mLocationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
boolean enabled = mLocationManager.isProviderEnabled(provider);
#SuppressLint("MissingPermission")
Location l = mLocationManager.getLastKnownLocation(provider);
if (l == null) {
Log.d("DebuggingLocation", "Skipped " + provider + " " + String.valueOf(enabled));
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
bestLocation = l;
}
}
return bestLocation;
}
Logs:
D/DebuggingLocation: Skipped passive true
D/DebuggingLocation: Skipped gps true
D/DebuggingLocation: Skipped network true
Problem solved by requesting location updates for passive, gps and network providers.
I want to get current GPS location when button is clicked. I have written this code (given below) but this gives NullPointerException for location object that is Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);. please tell what is problem with my code?
Code:
#Override
public void onClick(View v) {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
String cur_loc = "latitude = " + location.getLatitude() + "\n" + location.getLongitude(); //this is line 54 in my code
Toast.makeText(ctx, cur_loc, Toast.LENGTH_LONG).show();
}
AndroidManifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
getLastKnownLocation (String provider) may well return null. see Documentation :
Returns a Location indicating the data from the last known location
fix obtained from the given provider.
This can be done without starting the provider. Note that this
location could be out-of-date, for example if the device was turned
off and moved to another location.
If the provider is currently disabled, null is returned.
try this method:
private Location getLastKnownLocation() {
mLocationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);
List<String> providers = mLocationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = mLocationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
return bestLocation;
}
Now use it as:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location myLocation = getLastKnownLocation();
I am trying to retrieve Location as follows:
LocationManager locationManager = (LocationManager)MyApp.getAppContext().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
// Getting the name of the provider that meets the criteria
String provider = locationManager.getBestProvider(criteria, false);
if(provider!=null && !provider.equals("")){
// NOTE: the location below is null !!
Location location = locationManager.getLastKnownLocation(provider);
String lat = location.getLatitude();
String lng = location.getLongitude();
}
The 'location' above is null. Why?
But when i open the (Google) Maps app - it shows location correctly, and even a notification icon (looks like a exclamation mark) shows up.
And there is a GPS Coordinates app - which also shows up blank.
I have turned on Settings > 'Location' on the phone. If it matters this is Android 4.4.4 Sony Experia phone.
Well, it seems that you're not checking properly if the GPS is working or not. The way you should do it:
final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if (!manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
//GPS is not enabled !!
}
You can also create an AlertDialog so the user is aware that the GPS is not enabled and you can send him to the GPS settings by doing this:
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
After this, I'd implement a location listener and get coordinates, here is an example, check it out
How do I get the current GPS location programmatically in Android?
UPDATE: They might be getting coordinates through other provider (usually the one which is working better at that moment). So if the GPS it not working, just try other provider, here is an example:
Location lastKnownLocation = null;
List<String> providers = null;
if(locationManager != null) providers = locationManager.getAllProviders();
if(providers != null)
{
for(int i=0; i<providers.size(); i++)
{
if(locationManager != null) lastKnownLocation = locationManager.getLastKnownLocation(providers.get(i));
if(lastKnownLocation != null)
{
position = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
break;
}
}
}
public Location getLastKnownLocation() {
LocationManager mLocationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
List<String> providers = mLocationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = mLocationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null
|| l.getAccuracy() < bestLocation.getAccuracy()) {
bestLocation = l;
}
}
if (bestLocation == null) {
return null;
}
return bestLocation;
}
Why this function returns incorrect Location?? The mistake is about 8-9 kilometers
Because getLastKnownLocation doesn't return the current location. It returns the last location it figured out via that provider. That position could be an hour old- it will still return it, if it has it. If you want to get an accurate location you need to turn on the location provider by calling requestUpdates or requestSingleUpdate, then wait for the onLocationChanged function to be called at least once. Anything else may be a stale location.
It's because you're using getLastKnownLocation() : location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
getLastKnownLocation(String Provider) : Returns a Location indicating the data from the last known location fix obtained from the given provider.
This can be done without starting the provider. Note that this location could be out-of-date, for example if the device was turned off and moved to another location.
From : http://developer.android.com/reference/android/location/LocationManager.html#getLastKnownLocation%28java.lang.String%29
I've been pretty puzzled by this one. It seems as though my implementation of either Google Maps or pulling the users location is wonky. Right now I'm getting extremely scattered results across devices, and I'm not sure why, but the Lat/Long is Zeroing out on occasion.
Does anyone have any ideas?
Here is the method that I'm using to get my current location.
try {
locationListener = new MyLocationListener();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, locationListener);
loc = locationManager.getLastKnownLocation("gps");
if (loc == null) {
loc = locationManager.getLastKnownLocation("network");
}
if (loc != null && loc.getLongitude() != 0.0
&& loc.getLatitude() != 0.0) {
sLng = (loc.getLongitude());
sLat = (loc.getLatitude());
}
} catch (Exception e) {
e.printStackTrace();
}
You're using the last cached location. This is only reliable when GPS has been used recently (after the phone booted)
You have to use location obtained from the onLocationChanged() callback to get more up to date locations.