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.
Related
Last time I put the code on oncreate method which can successfully capture the device longitude and latitude but currently I run again and it show nothing please anyone can advice me on this question?
original should be can found in last month but currently cannot found!
The code is like this.
lm = (LocationManager) getSystemService(Context.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;
}
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000 , 0, (LocationListener) this);
//get Location
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
la = String.valueOf(location.getLatitude());
searchla.setText("Latitude: "+ la);
lo = String.valueOf(location.getLongitude());
searchlo.setText("Longitude: "+lo);
so did i miss out something?
If it was me, I would test to see if the longitude and latitude are returning values. Try putting break points and see.
If they are, it's problem for conversion and if not, it's problem with retrieval. Not the answer but gives the problem a direction to look into.
If there is no other code places that affects visibility of textviews, the only part is permission scope. So the device has no permission and then it goes to out of scope.
Maybe it seems a dummy answer but can you check if the location service (GPS) is activated on the emulator?
On the second screen shot I do not see the Location On icon.
If this is not the case:
Since last time you (when it worked) have you switched the API version? It is the same emulator/settings?
EDIT: Marshmallow emulator problem - https://issuetracker.google.com/issues/37069061
Solution: update to a newer API version
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 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'm trying to get the user's location within Android, the code below works however it always returns the same location no matter what I do. I've tested out in the middle of an empty parking lot to ensure the GPS is locked on, and it is. Google maps also shows my location correctly. Is there something wrong with the code below?
public class LocationTestActivity extends Activity implements LocationListener
{
private Location myLoc;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
output = (TextView) findViewById(R.id.output);
myLong = (TextView) findViewById(R.id.longi);
myLat = (TextView) findViewById(R.id.lat);
myRefreshed = (TextView) findViewById(R.id.counter);
mgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
#Override
public void onLocationChanged(Location location)
{
timesChanged++;
myRefreshed.setText("Refreshed: " + timesChanged);
myLong.setText("Longitude: " + location.getLongitude());
myLat.setText("Latitude: " + location.getLatitude());
}
}
I'd like to add that I can pass in a location using the emulator with no problem. I also removed the other needed methods required by LocationListener for clarity. Thanks for the help!
First make sure that onLocationChanged() is actually getting called. If your GPS has locked before then there is a chance that onLocationChanged won't get fired at all because the phone thinks that you haven't really moved. Therefore it is not a good practice to rely only on requestLocationUpdates() to get your current location.
In general here is what you should do to get your position:
You should use getLastKnownLocation() first to try locating your current location based on last known position.
Check if the location retrieved from step #1 is within reasonable time (not too old) by calling getTime() in the location and comparing with the current time
If this last known position is considered old (I normally use 5-10 minutes depending on the context of the app) then you start requestLocationUpdates() with specific distance (the app should make assumption that the user has moved within the specified limit of last known position)
Implement the onLocationChanged() as desired
Another note, I notice you are only using GPS, there is a lot of situation where GPS cannot lock and therefore never call onLocationChange(), your code should take account of that and checking Network based triangulation in the case onLocationChange() is not called within specified time
Try getting last location fix
Location loc = mgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
and give some time/distance between each location service request
mgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
And I hope you have enough patience to wait until your device retrieves the location and onLocationChanged() is triggered ;) Joking.
please check your manifest file whether have you added those permission or not.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
One more thing.Where did you call "removeUpdates()"?
So I'm trying to sample the gps coordinates just once in an application. I don't want to create a LocationListener object to constantly get gps updates. I want to wait until receiving the coordinates, and then proceed on to another task.
Here is a code snippet
LocationManager lm = (LocationManager)act.getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
String provider = lm.getBestProvider(crit, true);
Location loc = lm.getLastKnownLocation(provider);
The loc variable is always null in the emulator. I tried using the command "geo fix latitude longitude" to set it, and also I tried using the DDMS way of setting it. Neither method had any effect on the code. Also the snippet isn't causing any exceptions.
Thanks for your help.
The call to request update for a location is not blocking, hence it wont wait there. Also the provider in emulator may not have been started.
A possible check could be to see if the settings in it disable gps provider ? then send geo fix.
However, I would use Location Listener, it would be ideal in your case since you need a geo fix to proceed further.Location Listener is Used for receiving notifications from the LocationManager when the location has changed. You can unregister the listener after first geofix.
Note: It can take some time on device to get current location, and even on device this can return null.
Try using the MyLocationOverlay , create a runnable that does what you need to do with that GPS location, and pass it to
boolean runOnFirstFix(java.lang.Runnable runnable)
Queues a runnable to be executed as soon as we have a location fix.
and then disable the location updates for the MyLocationOverlay.
Edit: The reason the location is null is because at the time that code is run, no geofix has been received.