LocationManager sending null - android

I am using Google Map V2 and i trying to get the current location.But it is always returning null .
Code
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
Every time i am getting location null .My GPS is working fine in my device what can the issue please help me.

Per the getLastKnownLocation documentation:
If the provider is currently disabled, null is returned.
as you are using getBestProvider(criteria, false) you are saying you allow providers that are not enabled (that's what false means) - switch it to true if you only want to look at enabled providers (which will assure that getLastKnownLocation does not return null).
Note that the getLastKnownLocation could be very out of date and you may still want to look for location updates if you need to get a recent location.

There are different approach. First of all be sure that you have all required permission in your manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
If you only want an approximate location you can get the lastlocation (GPS or NETWORK)
if(_locationManager != null)
{
if(_locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER) != null)
return new Location(_locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER),true);
else if(_locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER) != null)
return new Location(_locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER),true);
}

Related

Android LocationManager locationManager.requestLocationUpdates() not working

hi guys i am trying to get current location with location manager, i am using this below code
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider =locationManager.getBestProvider(criteria,true);
Location location =
locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 20000, 0,this);
But i am not getting any response for this line
locationManager.requestLocationUpdates(bestProvider, 20000, 0,this);
and also getting lastknown location as null, i have added all permissions in manifest as well as dynamic, but this above line is not giving any response, i searched for it but dint get and relevant answer , please help.
For the getLastKnownLocation method, it is said in the documentation :
If the provider is currently disabled, null is returned.
Which means your GPS is disabled.
For the requestLocationUpdates, you are requesting a location every 20 seconds, try to decrease this number so you know at least if your program is working.
You can try this :
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
Also I really advise you to use the new API to request location updates : https://developer.android.com/training/location/receive-location-updates.html
It is very fast and accurate, but you need to create a google developer account (for free) and create an api key. All needed information should be in the link.
String bestProvider =locationManager.getBestProvider(criteria,true);
In the above line, the second boolean parameter is true. That means it will fetch the provider which is enabled. And you the GPS_PROVIDER is disabled which is validated by the fact that locationManager.getLastKnownLocation returns null.
Moreover, since your Criteria for requesting BestProvier is empty so you must be getting "passive" as your BestProvider. Which means you will receive location updates only when other applications request and receives updates.
To get real location updates in onLocationChangedMethod() of your class. You must ensure these things:
Make sure that you have either one of ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION and then request it in runtime too, which you say you have already done.
If you want to request location through GPS_PROVIDER then you need to make sure that GPS_PROVIDER is enabled you can do that using below code:
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); // OR some other PRIORITY depending upon your requirement
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(googleApiClient,
builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult locationSettingsResult) {
final Status status = locationSettingsResult.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can
// Request for location updates now
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied, but this can be fixed
// by showing the user a dialog.
status.startResolutionForResult(YourActivity.this, 100); // First parameter is your activity instance
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way
// to fix the settings so we won't show the dialog.
Log.e("TAG", "Error: Can't enable location updates SETTINGS_CHANGE_UNAVAILABLE");
break;
}
}
});
LocationManager.NETWORK_PROVIDER need network, but it is real, not precise.
if you want to use LocationManager.GPS_PROVIDER, the situation must be outdoor instead of indoor, because GPS location need satellite, if you are in any building, the satellite cannot find you!
pleasle go outdoor and check with GPS_PROVIDER again!
*best approach is getting location from both of GPS and NETWORK and check any of then that was not null and more accurate useing it.

Android using LocationManager Get Provider is "Passive" in My Moto G Android Phone

I need a little help with some information about LocationManager in Android. I'm using this code to get user's specific information depending on his location,but in My Device Motorola G I get provider="Passive" and also Location return Null My Motorola G is running on Latest Android Kit Kat(4.4) Android Os.
I also try this code in Other Devices so Provider is either Network Or GPS also find Location properly.
locationManager = (LocationManager) getSherlockActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(true);
criteria.setBearingRequired(true);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(provider, 1000, 0, this);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
Toast.makeText(getSherlockActivity(), "Location not available", Toast.LENGTH_SHORT).show();
}
I know that this is somehow an old question. But hope my answer will help others as well.
The issue is not related to the used device, actually the issue is how we use the provided API.
In the following code snippet, you pass true for the enabledOnly flag while you just need to pass it as false and it will work correctly at this time.
Instead of :
provider = locationManager.getBestProvider(criteria, true);
To be:
provider = locationManager.getBestProvider(criteria, false);
To clear this point:
If we set this flag "enabledOnly flag" to true, this means to return the requested best provider based on our criteria from the enabled only providers which will return the Passive provider.
While, if we set it to false, this will mean to return the requested best provider based on our criteria even if it is not enabled, which will return gps.
Btw, I am using Moto G too -but it's 2nd Gen- , and it worked with me this way :)
Hope this helps :)
READ THIS IF YOUR APP SUPPORTS kITKAT(4.4) VERSION OF ANDROID
I was having the same issue and my code was working perfectly in other devices not running kitkat,after a little bit of snooping around i found out that you have to explicitly turn on GPS to get location through wifi/gps. you can read about it here.
https://support.google.com/nexus/answer/3467281

Tower location in Android

Below is my code:
private Location getLastKnownLoaction(boolean enabledProvidersOnly){
LocationManager manager = mActivityContext.getSystemService(Context.LOCATION_SERVICE);
Location location = null;
List<String> providers = manager.getProviders(enabledProvidersOnly)
for(String provider : providers){
location = manager.getLastKnownLocation(provider);
//maybe try adding some Criteria here
if(location != null) return location;
}
//at this point we've done all we can and no location is returned
return null;
}
I have seen tower location being displayed in older Nokia phones. How do I implement similar functionality in Android?"
Make sure you have this on your manifest
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
And also must try it on real device not simulator.
It is not possible to get only tower location in android. What you can do is following :
In your manifest, add permission :
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
and in your code, use
Location location = manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
It helps you retrieve network based location. If its course, It will provide you with Tower based location most probably.
Also if you get a null in getting last location, you can request for a new location.

getLastKnownLocations always returns null

I am unable to getLastKnownLocations on my Android device (Samsung Galaxy Note N7000) as it is always null, towers is detected as network so it is fine, anybody got any idea how to get my location?
d = getResources().getDrawable(R.drawable.songs_gray);
//Placing pinpoint at location
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
towers = lm.getBestProvider(crit, false);
Toast.makeText(LocationActivity.this, "Towers: " + towers, Toast.LENGTH_SHORT).show();
Location location = lm.getLastKnownLocation(towers);
Toast.makeText(LocationActivity.this, "Location: " + location, Toast.LENGTH_SHORT).show();
if(location !=null){
lat = (int) (location.getLatitude()*1E6);
longi = (int) (location.getLongitude()*1E6);
GeoPoint ourLocation = new GeoPoint(lat, longi);
OverlayItem overlayItem = new OverlayItem(ourLocation, "What's up", "2nd String");
CustomPinpoint custom = new CustomPinpoint(d, LocationActivity.this);
custom.insertPinPoint(overlayItem);
overlayList.add(custom);
}else{
Toast.makeText(LocationActivity.this, "Couldn't get provider", Toast.LENGTH_SHORT).show();
}
Manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
With getLastKnownLocation() you can only get a Location object when the specified location provider is active.
The documentation says:
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.
To detect the current position and not the last detected one you need to enable the location provider(s). This tutorial should help you to understand how to work with location providers as GPS and network.
the last known location is only available if the location has been determined by another app prior to your call. start maps or some other app and let it get a location lock. then run your app.
if you really need location in your app, you need to fall back to some other method, because you cannot depend on there being a last known location.
as a side note, ACCESS_MOCK_LOCATION isn't required here. from the docs,
Allows an application to create mock location providers for testing
Nevermind found out my problem! Just needed to on Google's Location Services on my phone

Android Gps location

I enabled the GPS in my device but I am not getting the loaction:
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
if(lm.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location!=null)
{
showCurrentAddress(location);
}
}
But here I am gettin location is null and I added the following permissions to my code:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Could you please help?
lm.getLastKnownLocation can return null because that is a getter for the last known location.
Try using lm.requestLocationUpdates(LocationListener).
Hi check this tutorial for GPS location , i am also using this code for getting latitude and longitudeUsing GPS to get current location – Android tutorial check this on your device not on emulator first time just wait for few seconds..

Categories

Resources