I want the exact location of user. So I created two listeners as:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mGPSListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mNetworkListener);
I am listening for location updates from both the network and gps providers and wanted to check the accurary of locations obtained by both so that I can pick the accurate location. I just want to ask am I using the right way of acheiving that...??? if not, please provide some guideline how to do this...???
My example code is:
if(MyGPSListener.currentLocation != null) {
if(MyNetworkListener.currentLocation != null) {
if(MyGPSListener.currentLocation.getAccuracy() <= MyNetworkListener.currentLocation.getAccuracy()) {
useGPSLocation();
}
else if(MyGPSListener.currentLocation.getAccuracy() > MyNetworkListener.currentLocation.getAccuracy()) {
useNetworkLocation();
}
}
else {
useGPSLocation();
}
}
else if(MyNetworkListener.currentLocation != null){
useNetworkLocation();
}
You should take a look at: http://developer.android.com/guide/topics/location/obtaining-user-location.html
Especially the function: isBetterLocation
I would probably use something like the isBetterLocation. Since it's actually quite important to see how old the location updates are. At least if you really want to know where the user is know and not where the user were.
But you can surely implement a time check in your own function which you described.
You can use https://github.com/balwinderSingh1989/androidBestLocationTracker
Android Best Location Tracker is an Android library that helps you get user best location with a object named BaseLocationStrategy that would give a accurate location using accuracy alogrithm.
It has added support till latest android api levels and can fetch location in background with ease.
For usage, refer "READ ME" of project.
You can check Google's offical document.
Define a model for the best performance
And Validate the accuracy of a location fix:
Check if the location retrieved is significantly newer than the previous estimate.
Check if the accuracy claimed by the location is better or worse than the previous estimate.
Check which provider the new location is from and determine if you trust it more.
Related
I am developing an android application in which I need to get my current Location. I have successfully wrote the code and I am getting my current location using Google Play Service.
The problem is sometimes it gives me the location after a long time. I have noticed that it was only for first use of the app.
Any way to avoid this problem and get the current location fast? Is it related to the version of google play service in my code? (I am not using the last one in fact I am using version 9.8.0.)
As #tahsinRupam said, avoid using getLastLocation as it has a high tendency to return null. It also does not request a new location, so even if you get a location, it could be very old, and not reflect the current location. You might want to check the sample code in this thread: get the current location fast and once in android.
public void foo(Context context) {
// when you need location
// if inside activity context = this;
SingleShotLocationProvider.requestSingleUpdate(context,
new SingleShotLocationProvider.LocationCallback() {
#Override public void onNewLocationAvailable(GPSCoordinates location) {
Log.d("Location", "my location is " + location.toString());
}
});
}
You might want to verify the lat/long are actual values and not 0 or something. If I remember correctly this shouldn't throw an NPE but you might want to verify that.
Here's another SO post which might help:
What is the simplest and most robust way to get the user's current location on Android?
I'm trying to set some protection against people using mock locations to manipulate my app. I realise that it's impossible to prevent 100%... I'm just trying to do what I can.
The app uses Google location services (part of play services) in its main activity.
The onLocationChanged() method is:
public void onLocationChanged(Location location) {
this.mCurrentLocation = location;
if (Build.VERSION.SDK_INT > 17 && mCurrentLocation.isFromMockProvider()) {
Log.i(TAG, "QQ Location is MOCK");
// TODO: add code to stop app
// otherwise, currently, location will never be updated and app will never start
} else {
Double LAT = mCurrentLocation.getLatitude();
Double LON = mCurrentLocation.getLongitude();
if ((LAT.doubleValue() > 33.309171) || (LAT.doubleValue() < 33.226442) || (LON.doubleValue() < -90.790165) || (LON.doubleValue() > -90.707081)) {
buildAlertMessageOutOfBounds();
} else if (waiting4FirstLocationUpdate) {
Log.i(TAG, "YYY onLocationChanged() determines this is the FIRST update.");
waiting4FirstLocationUpdate = false;
setContentView(R.layout.activity_main);
startDisplayingLists();
}
}
}
The location services work perfectly and all is well with the app in general, but when I run the app in an emulator with Android Studio (Nexus One API 23), and I set the location using extended controls (mock), the app just continues to work as normal, and so it seems that the condition:
if (Build.VERSION.SDK_INT > 17 && mCurrentLocation.isFromMockProvider())
Is returning false.
This doesn't make any sense to me. Does anyone know why this would happen?
Thanks!
The short answer: .isFromMockProvider is unreliable. Some fake locations are not properly detected as such.
I have spent an extensive amount of time researching this and written a detailed blog post about it.
I also spent time to find a solution to reliably suppress mock locations across all recent/relevant Android versions and made a utility class, called the LocationAssistant, that does the job.
In a nutshell (using the aforementioned LocationAssistant):
Set up permissions in your manifest and Google Play Services in your gradle file.
Copy the file LocationAssistant.java to your project.
In the onCreate() method of your Activity, instantiate a LocationAssistant with the desired parameters. For example, to receive high-accuracy location updates roughly every 5 seconds and reject mock locations, call new LocationAssistant(this, this, LocationAssistant.Accuracy.HIGH, 5000, false). The last argument specifies that mock locations shouldn't be allowed.
Start/stop the assistant with your Activity and notify it of permission/location settings changes (see the documentation for details).
Enjoy location updates in onNewLocationAvailable(Location location). If you chose to reject mock locations, the callback is only invoked with non-mock locations.
There are some more methods to implement, but essentially this is it. Obviously, there are some ways to get around mock provider detection with rooted devices, but on stock, non-rooted devices the rejection should work reliably.
I simply need to get the user location. Preferably the exactly location, but if it's not possible, a rough location would be fine.
According to the docs:
LocationClient.getLastLocation()
Returns the best most recent location currently available.
and
LocationManager.getLastKnownLocation(String)
Returns a Location indicating the data from the last known location fix obtained from the given provider.
If my understanding is right, the former will give me a very good result (or null sometimes) while the latter will give me a result which would rarely be null.
This is my code (simplified)
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationClient = new LocationClient(this, this, this);
#Override
public void onConnected(Bundle dataBundle) {
setUserLocation();
}
private void setUserLocation() {
myLocation = locationClient.getLastLocation();
if (myLocation == null) {
myLocation = locationManager.getLastKnownLocation(locationManager.getBestProvider(new Criteria(), false));
if (myLocation == null) {
//I give up, just set the map somewhere and warn the user.
myLocation = new Location("");
myLocation.setLatitude(-22.624152);
myLocation.setLongitude(-44.385624);
Toast.makeText(this, R.string.location_not_found, Toast.LENGTH_LONG).show();
}
} else {
isMyLocationOK = true;
}
}
It seems to be working but my questions are:
Is my understanding of getLastLocation and getLastKnownLocation correct?
Is this a good approach?
Can I get in trouble using both in the same activity?
Thanks
LocationClient.getLastLocation() only returns null if a location fix is impossible to determine. getLastLocation() is no worse than getLastKnownLocation(), and is usually much better. I don't think it's worth "falling back" to getLastKnownLocation() as you do.
You can't get into trouble using both, but it's overkill.
Of course, you have to remember that LocationClient is part of Google Play Services, so it's only available on devices whose platform includes Google Play Store. Some devices may be using a non-standard version of Android, and you won't have access to LocationClient.
The documentation for Google Play Services discusses this in more detail.
I need to check if the GPS system is present on an android device.
I have seen the reply to the following question ,
How to check for the presence of a GPS sensor? ,but need to do it with an API level of 3 or 4.
The answer present on the link will work with a minimum of API Level of 5 for
hasSystemFeature() and 8 for the PackageManager.FEATURE_LOCATION_GPS constant.
Thanks in advance.
Update :
Used the following code, implementing the solution from CommonsWare.
boolean gpsOnBoard;
LocationManager locMan = (LocationManager) mCtx.getSystemService(Context.LOCATION_SERVICE);
List<String> locProvs = locMan.getProviders(true);
// check if we have a valid list of providers
if (locProvs != null)
{
gpsOnBoard = false;
// check all providers
for (String locProvName:locProvs)
{
if (locProvName.equals(LocationManager.GPS_PROVIDER))
{
// we have GPS hw onboard
gpsOnBoard = true;
}
}
Call getProviders() on the LocationManager and see what providers are there.
Ideally, you do not hard-code GPS support in your app, as users might have that provider disabled, even if the hardware exists. Consider using Criteria and another flavor of getProviders() to allow Android to help you find an appropriate and available provider.
I know this has been asked a ton, so my apologies. I have the following code, and cannot get the location, always a null response. I am trying to avoid a LocationListener in this instance because I am already using an update Service, and the location really doesn't have to be that fine, so the last known location is good enough. Thanks for the help.
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
String providers[] = {"gps", "network", "passive"};
Location loc = null;
for(String x : providers) {
loc = lm.getLastKnownLocation(x);
if(loc != null) break;
}
if(loc != null) {
// do something, never reached
}
I have the following code, and cannot get the location, always a null response.
Of course.
I am trying to avoid a LocationListener in this instance because I am already using an update Service
I have no idea what this means, but I suspect that you will need a LocationListener whether you like it or not.
Android is not constantly checking your location. Particularly with GPS, that would be horrible for the battery. Android only checks your location when somebody is using requestLocationUpdates() or addProximityAlert().
I'm not sure but maybe this happens because you use an emulator?
I remember I've tried to check last known location and have something like yours error.
So I always check getLastKnownLocation(provider) != null before use it.