I am using the following code to determine the current location when a proximity alert fires:
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location == null) {
// We'll just write an empty location
location = new Location("");
}
}
When I look at the locations that I get back I get entering alerts in locations where I should't get them. I was under the impression since proximity alerts internally poll the GPS and network provider - thus updating the LastKnownLocation - that this code would yield the current location. Is this assumption correct?
I am using the following code to determine the current location and its working too. Check out dis code...
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(context);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
if (null != provider)
{
Location location = locationManager.getLastKnownLocation(provider);
if (null != location) {
GpsFound=true;
currentLat = location.getLatitude();
currentLon = location.getLongitude();
System.out.println("Current Lat,Long :"+currentLat+" ,"+currentLon);
}
else
{
//GpsFound=false;
gpsMsg="Current Location can not be resolved!";
}
}
else
{
gpsMsg="Provider is not available!";
//GpsFound=false;
}
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 am trying to display the speed of the user on google glass live card.
I am able to get latitude and longitude,But getSpeed() always returns 0.0. I have checked similar questions on SO ,but of no help.
Here is my Code
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
LocationManager mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
String provider = mLocationManager.getBestProvider(criteria, true);
boolean isEnabled = mLocationManager.isProviderEnabled(provider);
if (isEnabled) {
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
if (location != null) {
Geocoder geocoder = new Geocoder(Start_service.this.getBaseContext(), Locale.getDefault());
// lat,lng, your current location
List<Address> addresses = null;
try {
lati= location.getLatitude();
longi=location.getLongitude();
speed=location.getSpeed();
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
}
catch (IOException e) {
System.out.println(e);
e.printStackTrace();
}
Location providers don't guarantee to provide the speed value. You can only getSpeed from the provider that calls setSpeed. You can set the Criteria variable to indicate that you need the speed value.
Criteria criteria = new Criteria();
criteria.setSpeedRequired(true);
Or you might consider to calculate it yourself. See why getSpeed() always return 0 on android.
Also, use hasSpeed() to check if a speed is available.
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.
I would like to know how can I get location from the best provider
do I have to make two separate criteria 1 for the GPS and 1 for the network or is there a way to put them all together ?
this is my code when I add the COARSE criteria the GPS does not go on (no GPS flashing logo on the top of the screen) and when I use the FINE criteria I dont get any thing from the network.......so do I have to write criteria for both and switch between them for what ever is available or can they both be in the same criteria ?
because I have the "getBestProvider(criteria, true);" in my code so it should get the location from the best provider....right..??!
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
//// criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_HIGH);
String provider = locationManager.getBestProvider(criteria, true);
Using a getBestProvider with Criteria.ACCURACY_FINE will never return the NETWORK_PROVIDER, even though wifi position is usually quite accurate.
In my application, I use getProviders to get all providers matching my criteria, then add the NETWORK_PROVIDER if it is activated and not yet in the list.
Then I launch a requestLocationUpdates for each of these providers, making sure to call removeUpdates when I get a location accurate enough.
This way, if the location provided by the network is accurate enough, the gps provider will be turned off
#nicopico getBestProvider with Criteria.ACCURACY_FINE can return the NETWORK_PROVIDER if gps is not enabled
i use the following code in my app
public void getLocation() {
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context);
// boolean network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// Showing status
if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available
Log.e(TAG, "getLocation fired Google Play Services are not available");
mHandler.post(new UiToastCommunicaton(context.getApplicationContext(),
context.getResources().getString(R.string.gpserv_notfound)));
}
// Getting LocationManager object from System Service LOCATION_SERVICE
locationManager = (LocationManager) context.getSystemService(IntentService.LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {//check if network location provider context on
Log.e(TAG, "network location provider not enabled");
} else {
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
//criteria.setPowerRequirement(Criteria.POWER_LOW);
// Getting the name of the best provider
provider = locationManager.getBestProvider(criteria, true);
// Check provider exists then request for location
if (provider != null) {
requestLocation(locationManager, provider);
} else {
//start wifi, gps, or tell user to do so
}
}
}
public void requestLocation(LocationManager locationManager, String provider) {
Log.e(TAG, "requestLocation fired getting location now");
if (provider != null) {
locationManager.requestLocationUpdates(provider, 0, 0, this);
//locationManager.requestLocationUpdates(provider, 0, 0, this, Looper.getMainLooper());
} else {
//tell user what has happened
}
}
this code is in a class that implements locationListener
you can edit this line
locationManager.requestLocationUpdates(provider, 0, 0, this);
to reflect your implementation of locationListener