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;
}
}
}
Related
is android stores last location, if so is it possible to get the last location when GPS/Mobile Data/Wifi is off.
The last known location of the device provides a handy base from which to start, ensuring that the app has a known location before starting the periodic location updates.
check this link .its very useful to us.
http://www.androidwarriors.com/2015/10/fused-location-provider-in-android.html
You could use locationmanager
LocationManager locationManager = (LocationManager) getSystemService(getApplicationContext().LOCATION_SERVICE);
// default
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, false);//get bese location provider
if (provider != null && !provider.equals(""))
{
//check for permission
if ( ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
// Get the location from the given provider
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
String Latitude = "" + location.getLatitude();
String Longitude = "" + location.getLongitude();
}
}
}
You need permission
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
I have a problem with getting current location because, I have in my MainActivity the listener:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATE,
MINIMUM_DISTANCECHANGE_FOR_UPDATE,
new MyLocationListener()
);
And I have a second activity where I would, when i click on button, calculate distance from my location and gps coordinate that I will pass with distanceTo and return true if the distance is beetween 0 and 200.
So I have a function in SecondActivity
private boolean checkCoordinate(String gps) {
LocationManager lm = (LocationManager) getSystemService(App.getContext().LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return false;
}
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double currentLongitude = location.getLongitude();
double currentLatitude = location.getLatitude();
Location loc1 = new Location("");
loc1.setLatitude(currentLatitude);
loc1.setLongitude(currentLongitude);
String[] sep = gps.split(",");
double latitude = Double.parseDouble(sep[0]);
double longitude = Double.parseDouble(sep[1]);
Location loc2 = new Location("");
loc2.setLatitude(latitude);
loc2.setLongitude(longitude);
float distanceInMeters = loc1.distanceTo(loc2);
if(distanceInMeters < 200){
return true;
}else{
return false;
}
}
But the problem is that someTimes and maybe when I don't change my location the function:
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
return null, and I don't understand how know my current location because I have already set requestLocationUpdates.
so I how can know my current location?
getLastKnownLocation will return null if GPS based location is disabled in system or there was no GPS fix since system startup. If you want to ensure there is a location you can use the requestSingleUpdate-method, it will not return until there is a location available.
It might also be a good idea to not use the APIs based on specific provider name if it's not important to use a specific provider (usually it is not important how you got the location). The API contains methods that take a Criteria-object instead of a provider name and you can define very precisely what accuracy level etc. you want.
I have an application that used to locate a user's location with this code
public static Location getCurrentLocation(Context context) {
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Criteria c = new Criteria();
String provider = lm.getBestProvider(c, true);
Location location;
if (provider == null) {
location = new Location("gps");
location.setLatitude(U.LATITUDE);
location.setLongitude(U.LONGITUDE);
} else {
location = lm.getLastKnownLocation(provider);
if (location == null) {
location = new Location("gps");
location.setLatitude(U.LATITUDE);
location.setLongitude(U.LONGITUDE);
}
}
return location;
}
This code appears to only be returning the behavior when provider is null or location is null. My guess is that something changed in this code.
String provider = lm.getBestProvider(c, true);
I have some code very similar to yours and it stopped working on my device after the upgrade to Android 4.4 (i.e. getBestProvider returned null which it never did before).
I discovered the reason when I saw that another App displayed that the NetworkProvider wasn't available (although I had perfect connection to both wifi and 3G) and it could not get a GPS signal (obviously, because I was indoors). Then I toggled Android's location quick setting and a dialog popped up, asking me to agree to the new location management of Android 4.4 (see https://support.google.com/nexus/answer/3467281). Afterwards, my code worked as before.
My app just need to know user's country, and my app doesn't care where user moves.
All I want to know is :
When user start app, app will send user's approximately location(latitude and longitude) to server.
Here is my code with error. I try to send a string to getlocation function, and I hope it can return original string with adding latitude and longitude information.
private String getlocation (String url){
LocationManager status = (LocationManager) (this.getSystemService(Context.LOCATION_SERVICE));
if (status.isProviderEnabled(LocationManager.GPS_PROVIDER) || status.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Log.v("print","enable to locate");
} else {
Log.v("print","fail to locate");
}
Location location = status.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!=null){
Log.v("print","succed!!!##");
Double longitude = location.getLongitude();
String loc=Double.toString(longitude);
url=url+loc;
}
else{
Log.v("print","location return null");
}
return url;
}
I use network_provider, and it always print "enable to locate", then print "location return null"
So what's wrong with my code that my location always return null.
I use AVD manerger, and I also try GPS_PROVIDER. I use Emulator control to send Decimal on location control. It doesn't work ,too.
By the way, I set network and GPS permission,too.
So much thanks for help!
I am getting location by below code but enable " use wireless networks " in settings i.e ( through settings - Location services - use wireless networks)
public void getCurrentLocation() {
LocationManager locationManager;
String bestProvider;
// Get the location manager
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
Log.e(TAG, "Latitude: "+location.getLatitude()+" , Longitude: "+location.getLongitude());
}
In my application I want to get the location of the user and show it on a map (google maps).
In the settings of a android device you can check
Use Wireless networks
Use GPS satellites
When the user starts the mapactivity I show a dialog in wich the user can choose to get his current location or not.
Old code deleted
If the user wants to get his location I check if the gps is enabled. If not, I start the settings. Else I try to get the location. But even when GPS is active and "use wireless networks" not he won't get a location. Is there a solution to check if "Use wireless networks" is enabled. Or what part of my code I need to change to get location only by GPS signal?
Thanks
EDIT mycurrentcode:
boolean isGps = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean isNetwork = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGps && !isNetwork){
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
} else if(isGps && !isNetwork) {
String bestProvider = LocationManager.GPS_PROVIDER;
Location location = lm.getLastKnownLocation(bestProvider);
Toast.makeText(MapsTabActivitiy.this, "Location niet beschikbaar.", Toast.LENGTH_SHORT).show();
} else if(!isGps && isNetwork) {
String bestProvider = LocationManager.NETWORK_PROVIDER;
Location location = lm.getLastKnownLocation(bestProvider);
if(location == null){
location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
} else if (location != null){
mapcontroller.animateTo(new GeoPoint((int)(location.getLatitude()*1E6), (int)(location.getLongitude()*1E6)));
mapcontroller.setZoom(15);
}
}
else {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String bestProvider = lm.getBestProvider(criteria, false);
Location location = lm.getLastKnownLocation(bestProvider);
if(location == null){
location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
} else if (location != null){
mapcontroller.animateTo(new GeoPoint((int)(location.getLatitude()*1E6), (int)(location.getLongitude()*1E6)));
mapcontroller.setZoom(15);
}
}
So I check with isProviderEnabled for GPS_PROVIDER AND NETWORK_PROVIDER. And with the if, else if I change how to get the location. The only case I need to find is case 2 (else if(isGps && !isNetwork){}). Get the location by GPS signal.
You're getting the right provider using the Criteria class, but you can simple use the LocationManager.GPS_PROVIDER to request the location updates using only GPS. Change
String bestProvider = lm.getBestProvider(criteria, false);
to
String bestProvider = LocationManager.GPS_PROVIDER;
Hope this helps.