I'm trying to retrieve the device's current location using the device's GPS. When I register for updates (as shown below) for LocationManager.GPS_PROVIDER no updates are rolling, yet when I do the same for LocationManager.NETWORK_PROVIDER I get the updates.
I have tested it on my Android device (not the emulator). I have also made sure the GPS is on. Other apps (not mine) are able to access my location. What am I missing here?
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
locationRetrieved(location, this);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) { }
public void onProviderDisabled(String provider) { providerDisabled(); }
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
GPS start up is not an instant process. The receiver basically has to know the position of each of the GPS satellites in the constellation in order to calculate it's location
Are you first checking if there is a last known location which you can use? Most apps first check for it and then search for a location.
You should check wheter your phone is allowing the gathering of location with GPS.
Probabily what is happening is that in Settings -> Location you only have the checkbox for wireless location. If so, the GPS_PROVIDER doesn't work.
Related
Perhaps I am misunderstanding, but all the articles i've found for locationmanager and locationlistener in android refer to the onLocationChanged() method.
I want to get the current position of the user, not when it's changed. Am I using the right method? The locationchanged listener is working, and in the emulator runs the method when I change the location.
My app workflow is this:
-> App gets request from server for location
-> locationservice starts and stays on for 5 seconds to get the location
-> locationservice saves the location to preferences
-> locationservice stops
-> messaging service sends location to server
is a location listener the right method? will it still work if the user does not change location?
here's my location service:
public class MyLocationService extends Service {
public LocationManager locationManager;
public LocationListener mLocationListener;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#SuppressLint("MissingPermission")
public int onStartCommand(Intent intent, int flags, int startId){
locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MyLocationService.this).edit();
editor.putString("latitude", Double.toString(location.getLatitude()));
editor.putString("longitude", Double.toString(location.getLongitude()));
editor.commit();
System.out.println("Location got changed");
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
try {
locationManager.requestLocationUpdates(locationManager.getBestProvider(new Criteria(), true), 10000, 0, mLocationListener);
} catch (Exception e){
e.printStackTrace();
}
return START_STICKY;
}
}
but the location change is only registering when I do it as the service is open. How can I run that every time the service runs?
You will get the user's current position the first time LocationManager triggers LocationListener::onLocationChanged.
If you are interested only in the current location you can set up the LocationListener to receive the first location update and then stop.
public void onLocationChanged(Location location) {
// location gotten... store it somewhere
// and stop the location manager
locationManager.removeUpdates(this.locationListener);
}
Still, LocationListener::onLocationChanged will trigger depending on the criteria you have set to your LocationManager.
For instance:
this.locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this.locationListener);
will not be limited by any criteria, it will continuously request location updates.
is a location listener the right method? will it still work if the user does not change location?
Yes
How do my android cellphone get the a driving car speed from GPS?
Can you give me an example which it can get car location from GPS and get speed?
Any advice is a help.
Thank you very much.
The location has an attribute speed which you get by getSpeed() method.
The GPS receiver chip determines speed NOT by distance and time relation.
It uses the Doppler Shift Effect, which gives more precise speed.
The higher the speed, the more acurate it is. Under 10km/h it does not work well.
// 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) {
location.getLatitude();
Toast.makeText(context, "Current speed:" + location.getSpeed(),
Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, locationListener);
}
Using android locationmanager you can get latest last known location and in Location class getSpeed() method is there which will gve speed
the speed if it is available, in meters/second over ground.
If this location does not have a speed then 0.0 is returned.
Another way is find the distance between two location using location manager & provider and Location has one method to get distance in meter distanceTo(Location)
Convert Distance to meter and get the time From Location Class using getTime() and apply speed formula (speed = distance/time)
I use the function onLocationChanged to identify the user's location, I want it to happen every movement of Android phone
exactly when the function is called?
My code looks like this:
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new GPSLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
GPSLocationListener:
public class GPSLocationListener extends DroidGap implements LocationListener
{
#Override
public void onLocationChanged(Location location) {
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setMessage("onLocationChanged");
AlertDialog alert = alt_bld.create();
alert.show();
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
The alert onLocationChanged never appears.
According to this link:
http://developer.android.com/reference/android/location/LocationListener.html#onLocationChanged(android.location.Location) the method is called every time the location has changed.
From my observation there is some logic behind it and it does not change evvery time (e.g. when new location is nearby the old and has worse accuracy).
EDIT:
"every little movement" can be ACCURACY_HIGH at the most...I think you cant get more precise than this. Reference: http://developer.android.com/reference/android/location/Criteria.html#ACCURACY_HIGH
EDIT 2:
To use ACCURACY_HIGH create new Criteria object and use the setters (setHorizontalAccuracy, ...) and then use it like this
locationManager.requestLocationUpdates(locationManager.getBestProvider(locationCriteria, true), 1L, 2F, this);
It depends of arguments sent to:
requestLocationUpdates (String provider, long minTime, float minDistance, LocationListener listener)
minTime - minimum time interval between location updates, in milliseconds
minDistance - minimum distance between location updates,
in meters
Location updates are received by LocationListener callbacks
See here for more info.
From the documentation of
requestLocationUpdates(String provider, long minTime, float
minDistance, LocationListener listener)
concering the minTime parameter:
"the minimum time interval for notifications, in milliseconds. This
field is only used as a hint to conserve power, and actual time
between location updates may be greater or lesser than this value."
Also
public abstract void onLocationChanged (Location location)
Added in API level 1
Called when the location has changed.
There are no restrictions on the use of the supplied Location object.
Parameters
location The new location, as a Location object.
If this is a problem for you, you could ignore calls to the callback method if a certain amount of time hasn't passed.
Hope it will help you
When a location is changed .When a new location details is captured by gps receiver then the method
onLocationChanged(Location location)
is called automatically.
My location listener works when I am using the DDMS controls in the emulator but when I deploy it onto the phone it no longer works. My code is as follows
public class hoosheerAndroidAct extends MapActivity implements LocationListener {
/** Called when the activity is first created. */
MapController mc;
public static MapView gMapView = null;
GeoPoint p = null;
static double latitude, longitude;
MyLocationOverlay myLocationOverlay;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen1);
// Creating and initializing Map
gMapView = (MapView) findViewById(R.id.mapview);
p = new GeoPoint((int) (latitude * 1E6),
(int) (longitude * 1E6));
gMapView.setSatellite(true);
gMapView.setBuiltInZoomControls(true);
mc = gMapView.getController();
mc.setCenter(p);
mc.setZoom(11);
myLocationOverlay = new MyLocationOverlay(this, gMapView);
gMapView.getOverlays().add(myLocationOverlay);
list = gMapView.getOverlays();
list.add(myLocationOverlay);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 5.0f,
this);
}
methods implemented for implements LocationListener
public void onLocationChanged(Location location) {
if (location != null) {
GeoPoint point = new GeoPoint((int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));
mc.animateTo(point);
connect("http://api.foursquare.com/v1/venues.json?geolat="
+ location.getLatitude() + "&geolong="
+ location.getLongitude());
Drawable marker = getResources().getDrawable(R.drawable.marker);
gMapView.getOverlays().add(new SitesOverlay(marker));
}
}
public void onProviderDisabled(String provider) {
// required for interface, not used
}
public void onProviderEnabled(String provider) {
// required for interface, not used
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// required for interface, not used
}
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
Is there anything I am missing? :-(
Google maps will default to network location provider if the GPS is unable to find a signal so that test could return a location without a GPS signal. I would recommend GPS Status as a good free app. The only other thing I can think of is to make sure you have a clear view of the sky.
its because when your device is not able to find location it return default location 0,0. better you check your device gps connection by checking other apps like map app of your device
Maybe you are testing in door,can't get gps information. try to change LocationManager.GPS_PROVIDER-->LocationManager.NETWORK_PROVIDER.
I had a similar problem and try everything in programming. I read about that google use same other sensors to find location. I even find mobile where location listener won't work in google maps. When I checked the settings i accedently turn on battery power saving and location listener starts. On some other device where location wan't work too I turn on buttery saving and location is shown. I don't know why is that, but buttery maybe will save your app.
I read some tutorials online, and found that LocationManager does this.
This is the code I found online. However, I don't get it. Why can't I just get the long/lat? Why go through all the "change" location things...
lm=(LocationManager)this.getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10, 10, new LocationListener(){
#Override
public void onLocationChanged(Location location) {
Log.d("a","onLocationChanged: lat="+location.getLatitude());
Log.d("a","onLocationChanged: lat="+location.getLongitude());
}
#Override
public void onProviderDisabled(String provider) {
Log.d("a","onProviderDisabled: " +provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.d("a","onProviderEnabled: " +provider);
}
#Override
public void onStatusChanged(String provider, int status,Bundle extras) {
Log.d("a","onStatusChanged: " +provider + status);
}
});
By the way, this code doesn't work. When I run it in a timer...nothing happens. Nothing gets logged. I just want the longitude latitude!!
LocationManager can return a last known location but this is not very precise so you have to request location updates and wait for the first one. Then you can continue receiving them or cancel them. You can request both network and GPS updates.
If you are using a phone to test your code then you have to wait for a GPS fix, and this can take a while. Network provider should be much faster.
If you are using Eclipse, then you have to send artificial GPS updates using DDMS. You can't test a network provider from the emulator (you will never receive an update).