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.
Related
i implemented the method used in Lib android this, see:
fusedLocationProviderClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if(location != null) {
localidade = location;
Toast.makeText(getApplicationContext(), "Local correto", Toast.LENGTH_LONG).show();
}
Toast.makeText(getApplicationContext(), "Localidade vazia", Toast.LENGTH_LONG).show();
}
});
However, within OnSuccess the result is ALWAYS null, I am testing on my mobile (9.0 android) with LOCAL(gps) mode on and still returns null, my manisfest has the necessary permissions: <uses-permission android: name = "android.permission .ACCESS_FINE_LOCATION "/>
In my view nothing is wrong, so why ALWAYS null?
Last known location is registered known location by the user. If you read on the location page it states that last known location can be null in certain situations; in those scenarios it is advised you request location updates. Following is taken from the page:
The location object can be nullin the following situations:
Location is disabled in the device settings. The result may nulleven
be that the last location was retrieved earlier, because disabling the
location also clears the cache. The device never recorded its own
location, which happens when the device is new or when it has been
restored to factory settings. The Google Play Services platform on the
device has been restarted and no active Fused Location Provider API
clients have requested location after services have been restarted. To
avoid this situation, create a new customer and request location
updates.
Is it possible to get the current location of user without using GPS or the internet? I mean with the help of mobile network provider.
What you are looking to do is get the position using the LocationManager.NETWORK_PROVIDER instead of LocationManager.GPS_PROVIDER. The NETWORK_PROVIDER will resolve on the GSM or wifi, which ever available. Obviously with wifi off, GSM will be used. Keep in mind that using the cell network is accurate to basically 500m.
http://developer.android.com/guide/topics/location/obtaining-user-location.html has some really great information and sample code.
After you get done with most of the code in OnCreate(), add this:
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
makeUseOfNewLocation(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
You could also have your activity implement the LocationListener class and thus implement onLocationChanged() in your activity.
By getting the getLastKnownLocation you do not actually initiate a fix yourself.
Be aware that this could start the provider, but if the user has ever gotten a location before, I don't think it will. The docs aren't really too clear on this.
According to the docs getLastKnownLocation:
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.
Here is a quick snippet:
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import java.util.List;
public class UtilLocation {
public static Location getLastKnownLoaction(boolean enabledProvidersOnly, Context context){
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Location utilLocation = null;
List<String> providers = manager.getProviders(enabledProvidersOnly);
for(String provider : providers){
utilLocation = manager.getLastKnownLocation(provider);
if(utilLocation != null) return utilLocation;
}
return null;
}
}
You also have to add new permission to AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
No, you cannot currently get location without using GPS or internet.
Location techniques based on WiFi, Cellular, or Bluetooth work with the help of a large database that is constantly being updated. A device scans for transmitter IDs and then sends these in a query through the internet to a service such as Google, Apple, or Skyhook. That service responds with a location based on previous wireless surveys from known locations. Without internet access, you have to have a local copy of such a database and keep this up to date. For global usage, this is very impractical.
Theoretically, a mobile provider could provide local data service only but no access to the internet, and then answer location queries from mobile devices. Mobile providers don't do this; no one wants to pay for this kind of restricted data access. If you have data service through your mobile provider, then you have internet access.
In short, using LocationManager.NETWORK_PROVIDER or android.hardware.location.network to get location requires use of the internet.
Using the last known position requires you to have had GPS or internet access very recently. If you just had internet, presumably you can adjust your position or settings to get internet again. If your device has not had GPS or internet access, the last known position feature will not help you.
Without GPS or internet, you could:
Take pictures of the night sky and use the current time to estimate your location based on a star chart. This would probably require additional equipment to ensure that the angles for your pictures are correctly measured.
Use an accelerometer to track location starting from a known position. The accumulation of error in this kind of approach makes it impractical for most situations.
boolean gps_enabled = false;
boolean network_enabled = false;
LocationManager lm = (LocationManager) mCtx
.getSystemService(Context.LOCATION_SERVICE);
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Location net_loc = null, gps_loc = null, finalLoc = null;
if (gps_enabled)
gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (network_enabled)
net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (gps_loc != null && net_loc != null) {
//smaller the number more accurate result will
if (gps_loc.getAccuracy() > net_loc.getAccuracy())
finalLoc = net_loc;
else
finalLoc = gps_loc;
// I used this just to get an idea (if both avail, its upto you which you want to take as I've taken location with more accuracy)
} else {
if (gps_loc != null) {
finalLoc = gps_loc;
} else if (net_loc != null) {
finalLoc = net_loc;
}
}
Here possible to get the User current location Without the use of GPS and Network Provider.
1 . Convert cellLocation to real location (Latitude and Longitude), using "http://www.google.com/glm/mmap"
2.Click Here For Your Reference
Have you take a look Google Maps Geolocation Api? Google Map Geolocation
This is simple RestApi, you just need POST a request, the the service will return a location with accuracy in meters.
It appears that it is possible to track a smart phone without using GPS.
Sources:
Primary: "PinMe: Tracking a Smartphone User around the World"
Secondary: "How to Track a Cellphone Without GPS—or Consent"
I have not yet found a link to the team's final code. When I do I will post, if another has not done so.
You can use TelephonyManager to do that .
I am developing a location based app which have the functionality to update user current location in every 1 minutes.
I am using bellow to code for requesting location updates:
private LocationRequest mLocationRequest;
private static LocationClient mLocationClient;
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(60000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setFastestInterval(60000);
mLocationClient = new LocationClient(this, this, this);
if (servicesConnected()) {
mLocationClient.connect();
}
servicesConnected() is user defined method which returns true if Google play services is available otherwise returns false
and my overriden method like this:
#Override
public void onConnected(Bundle connectionHint) {
try {
mLocationClient.requestLocationUpdates(mLocationRequest, this);
} catch (IllegalStateException e) {
// TODO: handle exception
}
}
#Override
public void onLocationChanged(Location location) {
// logic to store location data
}
But I found location updates like bellow figure while my GPS is ON :
Please suggest what should I do to overcome unwanted location updates.
Here's some info from OwnTracks https://github.com/owntracks/android/issues/66
From my research the only thing you can do is filter out "bad" locations like this:
#Override
public void onLocationChanged(Location location) {
if(location.getAccuracy() < 210.0) {
// use provided location
}
}
It doesn't appear that there is any way to prevent these updates from being requested using the Fused provider (other than stopping updates or increasing the interval when you have a location you are satisfied with). There's only so much "filtering" that can be done by the GPS itself and those options are the constants inside LocationRequest that you already know about. I believe your issue is hardware related or has to do with the location you are getting updates from (I'm basing this assumption on the OwnTracks data). Google could theoretically offer more advanced Criteria like it used to do with LocationManager, but I believe that would basically do the same thing as my example, except under the hood (i.e. the GPS would still do the work of getting the location and then discard it AFTER it knows the accuracy isn't high enough).
If you want to make it do less work, your best options are increasing the interval or simply stopping updates when you no longer need new locations. For example, if you have a decent location, maybe you raise the interval and keep that location longer. But that depends on what your app is trying to do with the data.
I'm having little problem with getting my current location using NETWORK_PROVIDDER.
My code looks like this:
LocationManager lMgr = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
boolean isNetworkProviderEnabled = lMgr
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Location location = lMgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
// deal somehow with last (very likely outdated location)
}
if (isNetworkProviderEnabled) {
lMgr.requestLocationUpdates(provider, 0, 0, locationListener);
}
Of course I have MyLocationListener that deals with location changes and ALL REQUIRED PERMISSIONS ARE ADDED TO MANIFEST
And the problem is that on some phones this code works like charm, but one others, the "requestLocationUpdates" does totally nothing. Of course on those problematic phones, when I open Google Maps application, my current location appears immediately. So my question is (I believe that people from Google should answer this): how this is done that Google Maps retrieves current location immediately, and other apps don't? Is my code wrong? Of course I have seen code like this in many stackoverflow questions. If anyone wish to know, this kind of problem appears on some Samsung Galaxy Nexus S phones
In my application GPS is not used to save battery power, but location services are enabled.
I have recently faced the same issue, LocationManager is buggy and not implemented completely on Samsung phones. They also consume a lot of power. Use LocationClient to solve both these issues. LocationClient uses all means available to get you the last location, so its the super set of all your providers and sensors.
I faced issues with the Samsung Y model phones, I wonder which phones you are talking about. To fix the problem with Samsung phones, I kickstarted the GPS on the phone with
HomeScreen.getLocationManager().requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onLocationChanged(final Location location) {
}
});
And then called the LocationManager.getLastKnownLocation OR the new locationClient.getLastLocation api.
First, just add the above lines over your getLastKnownLocation. Things should magically start workings
Migrate to LocationClient when you have more time and test again. Use the magic above to get it working if it fails.
Sometimes device does not receive any location updates and GPS_PROVIDER and NETWORK_PROVIDER returns null.
Try restarting your device, this trick helped me. My code was perfectly fine but providers were returning null.
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.