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.
Related
In my app, I need to get the location of my users. Since my app is going to do it constantly, I want to change the location provider in certain conditions (between GPS and NETWORK providers). My app is going to detect such conditions and change it.
But, I'm not sure how to change it dynamically.
So far, I have a thread (that, among other things, will check for these conditions) and I want it to change the location provider too. My code until now is as below:
public void run() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationController = new LocationController();
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, time, desltaDistance, locationController );
while (serviceIsRunning) {
...
if (conditionsAreMet) {
locationManager.removeUpdates(locationController);
if (provider == LocationManager.GPS_PROVIDER)
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, time, desltaDistance, locationController );
else
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, time, deltaDistance, locationController );
}
...
}
}
*The LocationController class implements LocationListener.
But, it don't seems to be the better way to do it. So, what I want to know is: there is a better way to change the location provider automatically?
Since no one answered this question, here is how I figured it out.
Instead of make the change between the providers, I registered a constant controller for the NETWORK_PROVIDER. And, according to my conditions, a controller for the GPS_PROVIDER may be registered or not.
It's easier to register/unregister the locations request for one provider, instead of keep changing between them.
I have successfully implemented the android location example http://developer.android.com/training/location/retrieve-current.html
I can request location updates via button click and the onLocationChanged method will be triggered to update a map view with the current location.
But consider following problem. When the phones location does not change, onLocationChange will not be triggered anymore. When the user touches the map view and swipes to another location manually, another location request will not trigger onLocationChanged and the map view will not get the current location because the phones position has not changed.
My question is, how can I receive a location in onLocationChanged at 0 location difference? I am using LocationClient and LocationRequest classes and not LocationManager, so this wont work:
manager.requestLocationUpdates(best, 10000, 1, locationListener);
Any ideas?
use getLastLocation() mehod of locationClient it will give you last known location, however it may be null sometime, I observe in some devices it is returning null when I restart the device and call that function before starting gps or location client method.
in that case you can invoke getLastKnownLocation but you have to detect that state, simply try to wrap your class that provide you location and once time it is update with R
requestLocationUpdateslistening on updates and once when it is not triggered it invoke getLastKnownLocation
so simply you can wrap it with some class that contains lastLocation or best location field
public class MyLocationProvider implements LocalisationListener{
private Location bestLocation = null;
private LocationManager locationManager;
//constructor and all that stuff...
public Location getBestLocation(){
if(bestLocation == null)
return locationManager.getLastKnownLocation();
else
return bestLocation;
}
//locationListener methods... that should save their result in `bestLocation` field.
}
This is simple draft of my idea.... I didn't compile it ;)
http://developer.android.com/reference/android/location/LocationManager.html#getLastKnownLocation(java.lang.String)
I am developing a proximity alert related project. For that whenever I opened my app, I need to get exact readings of where I am. Even though I am following the right coding practices prescribed by android documentation, I am not getting the expected result.
Why there is no alternative command in entire android Geolocation coding for getLastKnownLocation which will give us where we are earlier not now.
I have did one javascript coding in the same lines. There My code is working properly. The Descriptive address and coordinates where my device is working nice there. Those commands getCurrentPosition and watchPosition are givinga beautiful response via their event handler callbacks. Why there is no getCurrentLocation in android geolocation parlance?
Even though I have followed relevant coding practices, MyLocationListener myLocationUpdate which implements LocationListener is not updating my new location when I am moving from one place to another place. I gave MINIMUM_DISTANCE_CHANGE_FOR_UPDATES as 1(in meters) and MINIMUM_TIME_BETWEEN_UPDATES as 1000 (in milliseconds).
I am giving important code snippets below to understand the problem
in onCreate handler of the activity
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
myLocationUpdate = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MINIMUM_TIME_BETWEEN_UPDATES,MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, myLocationUpdate);
retrieveLocationButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"Finding Location",Toast.LENGTH_LONG).show();
showCurrentLocation();
}
});
latituteField = (TextView) findViewById(R.id.display_Location);
showCurrentLocation();
in showCurrentLocation function
I am using locationManager.getLastKnownLocation(provider) to retrieving that location.
By using GeoCoder Object and the command geocoder.getFromLocation(latitude, longitude, 1) to get First Address match for the coordinates.
// internal class to handle location cahnge event
private class MyLocationListener implements LocationListener contains all the Overridden functions including public void onLocationChanged(Location location)
But Practically I am getting nothing out of all the application. I have already recorded Time via location.getTime(). It is showing a fixed earlier time, but not the interval i specified.
the problem with getting GPS location is that it isnt available immediately. From my understanding of GPS location provider is that when you request location update, the gpr provider will try to connect to the gps satellites which runs in a separate thread (not entirely sure about it). In the meantime your program is executed normally and there maybe a chance that you wont get any location.
What you can do is use Fused Location Provide which was introduced in this year's IO Event. You can find the tutorial here
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()"?
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.