i dont understand why locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); return the location null. I gave all permission but its reutning null.
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
I had this exact same problem. It was because my device was not storing a last known location. I simply went on to Google Maps and pinpointed my location with GPS, then a value was returned for getLastKnownLocation()
You can request location updates like this
mLocationManager.requestLocationUpdates(myProvider, 0, 0, locationListener);
then on the first callback in locationListener.onLocationChanged set your coordinates. Just don't forget to call mLocationManager.removeUpdates(locationListener)
Accoding to the documentation, it returns null, if the device is not aware of the last known location. Probably the GPS can not locate you. It takes about a minute or more, anyway. So try to go outside, under the clear sky, away from tall buildings, and wait until GPS can locate you.
I used this method for get location i think it will help you
private void startReceivingLocationUpdates() {
if (mLocationManager == null) {
mLocationManager = (android.location.LocationManager)
mContext.getSystemService(Context.LOCATION_SERVICE);
}
if (mLocationManager != null) {
try {
mLocationManager.requestLocationUpdates(
android.location.LocationManager.NETWORK_PROVIDER,
1000,
0F,
mLocationListeners[1]);
}
catch (SecurityException ex)
{
Log.i(TAG, "fail to request location update, ignore", ex);
}
catch (IllegalArgumentException ex)
{
Log.d(TAG, "provider does not exist " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
android.location.LocationManager.GPS_PROVIDER,
1000,
0F,
mLocationListeners[0]);
if (mListener != null) mListener.showGpsOnScreenIndicator(false);
}
catch (SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex); }
catch (IllegalArgumentException ex) {
Log.d(TAG, "provider does not exist " + ex.getMessage()); }
Log.d(TAG, "startReceivingLocationUpdates");
}
}
When you use GPS as provider then it gives your result with in 1 to 2 mnts so you have to contentiously check for that when get location stop and Network Provider gives you immediate locationwhen you request. So you dont get immediate Location lat lon in GPS provider.
GPS take 1 to 2 only first time then after it will give location you on call...
Related
I'm creating an app that needs to know the users coarse location and on every other phone I've tested this works fine but on my xperia X performance, getLastKnownLocation() always returns null without exception.
This code works on other devices and the gps works on my phone with other apps.
public boolean startLocationManager() {
// Check for permission to use Fine Location
if (ContextCompat.checkSelfPermission(mActivity,
Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
try {
locationManager = (LocationManager) mActivity.getSystemService(LOCATION_SERVICE);
String providerInfo = null;
// Check if Network provider is enabled
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
providerInfo = LocationManager.NETWORK_PROVIDER;
}
else{
showSettingsAlert();
}
// Application can use GPS or Network Provider
if (providerInfo != null) {
locationManager.requestLocationUpdates(
providerInfo,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,
this
);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if(location != null){
isEnabled = true;
}
else{
Toast.makeText(mActivity, R.string.location_is_turned_off, Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "Can't connect to LocationManager", e);
}
}
return isEnabled;
}
I've given the app the right permissions and I still can't get anything but null from getLastKnownLocation().
I don't know if it's of any help but heres some phone info:
Phone info
if (providerInfo != null) {
locationManager.requestLocationUpdates(
providerInfo,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,
this
);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(
LocationManager.NETWORK_PROVIDER);
}
It's not guaranteed to get location from getLastKnownLocation, because it retrieves previously cached location if any. You have to wait until onLocationChanged callback is fired
I wanted to get my GPS coordinates using Android App. I started developing, and I can get GPS coordinates, but they are not accurate. I wanted to use NETWORK_PROVIDER, but the Location by this provider is always null. More interesting, isProvicerEnabled returns true.
I used example from this thread (best answer)
enter link description here
private void _getLocation() {
// Get the location manager
try {
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
Location location = null;
double latitude = -1;
double longitude = -1;
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
if (isNetworkEnabled) {
showToast("network");
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
1000,
0, this);
Log.d("Network", "Network Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
else if (isGPSEnabled) {
showToast("gps");
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
1000,
0, this);
Log.d("GPS", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
showToast("" + latitude + longitude);
} catch (Exception e) {
e.printStackTrace();
}
I have all the permissions in manifest
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
I know the code is dirty, but for now it's only for testing. Do I miss something? I found similar examples in many places, and it seems pretty straight, so I am a little confused.
My phone works ok, GPS and network works fine. For example Google Maps application I have works well. Any suggestions?
Please do NOT use this code. It's bad. It has a lot of errors. Also, getLastKnownLocation will return null if it doesn't have a location yet. Which it always will if nobody on the phone is using requestUpdates.
Your code is taken from a class that was posted on a very old thread on here called GPSTracker. I've been trying to kill that code for months- it causes far more problems than it helps. If you want better example code, try http://gabesechansoftware.com/location-tracking/ which is a blog post I wrote about how bad that code is. It will show you the correct way to do it, and explains some of what's wrong with that code.
I've been working on an application that tracks a users GPS coordinates and intermittently sends updates to my server. This is done in a thread within a service. Most of the time the first reading will be accurate but when moving the GPS is not updating. I think this is because the LocationManager takes some time to warm up. The location setting on the device will also affect the outcome (Device only, high accuracy), sometimes resulting with 0.0 being returned. Is there a simple solution that will allow it enough time before the values are decided upon?
Service thread:
new Thread() {
public void run() {
// prepare looper
Looper.prepare();
// send text messages
String numbersList = helper.getNumbers();
if (numbersList != "") {
String numbersArray[] = numbersList.split(", ");
for (int i = 0; i < numbersArray.length; i++) {
sendSMS(numbersArray[i], incident_id);
}
}
// run until told otherwise
while (active == true) {
// check if GPS enabled
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
accuracy = gps.getAccuracy();
} else {
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
GPS Tracker Class:
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
else if(isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
Your first location always is the last known location (locationManager.getLastKnownLocation(...)). This location may be relativly old, for example the last fix of the GPS before it was turned off or before you entered a building. Its accurracy in relation to your current location is more or less random (unless you did not move or left the building using the same door).
If the GPS was turned off or the satellites were not visible for a while (e.g. inside a building) the hardware will need some time to get a fix on the current location. This is the delay you are seeing. Afterwards your location listener (not shown above) will get updates from the GPS.
I've got Google Maps v2 running on my app, using a service to get the users location. Problem is the location keeps changing. It shows my real location for a bit, then jumps to a random location that I've never been to before.
I'm check GPS/Network lat/lng via the service and calling them in my maps class, where I then animate the camera to move to my location. I don't really know what's wrong, or where to start with this one.
Does anyone know what sort of problem this is? It's baffling to me.
I don't really know what code to post. The accuracy of the location via network is 1121m where as the accuracy of the location via GPS is around 31. I'm using a LocationListener and in the onLocationChanged is says it's using my network location, suddenly the accuracy improves, to 29m, then it suddenly goes back up to 1121m. This happens about every minute or so. Very odd behaviour. With GPS enabled, shouldn't that be the preferred choice anyway? Is there a way to set it to my preferred choice once it gets a fix?
My service gets it's information like this:
public Location getLocation() {
Log.i("getLocation", "Get location called");
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
//Getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//Getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled and GPS is off.
Log.d("NOT ENABLED", "PASSIVE PROVIDER");
locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
loc = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
if (loc != null) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
Log.i("PASSIVE_LOCATION", "Location: "+loc.toString());
}
}
else {
this.canGetLocation = true;
if (isNetworkEnabled) {
Log.d("Network", "Network");
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (loc != null) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
Log.i("NETWORK_LOCATION", "Location: "+loc.toString());
}
}
if (isGPSEnabled) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc != null) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
Log.i("GPS_LOCATION", "Location: "+loc.toString());
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
//check provider & accuracy
Log.d("PROVIDER", loc.getProvider());
Log.d("ACCURACY", Float.toString(loc.getAccuracy()));
return loc;
If anyone could help I would really appreciate it. Thank you in advance.
I think this solved itself. It was jumping between locations simply because of accuracy. Once GPS accuracy was better than network, it started updating via GPS.
I'm also stopping location updates once the accuracy is less than 30 in onLocationChanged so I have a bit more control and don't waste the users battery.
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.