Reputation: 226
I'm trying to obtain my current location via GPS, but nothing seems to work, I followed many questions here but with little results...
Here's my code:
private GeoPoint getActualPosition()
{
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
Location current = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
actualLat = (int)(current.getLatitude()*1E6);
actualLong = (int)(current.getLongitude()*1E6);
GeoPoint point = new GeoPoint(actualLat, actualLong);
return point;
}
Now, the "this" part of the method (on requestLocationUpdates) makes reference to the activity who implements the LocationListener interface, where its onLocationChanged method is:
@Override
public void onLocationChanged(Location location) {
actualLat = (int)(location.getLatitude()*1E6);
actualLong = (int)(location.getLongitude()*1E6);
}
My problem is on the current Location line, where "current" is always, always null, and I can't find why.
My manifest has the permissions needed:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
So I don't really know what is wrong with my code.
Thank you for your time!!
Upvotes: 0
Views: 1124
Reputation: 2982
are you running the app / your code on an emulator or a physical device ? If its an emulator and you never set the location before (using DDMS view inside eclipse), the location will be null.
hope this helps.
Upvotes: 1
Reputation: 33792
getLastKnownLocation()
returns the last cached location. If there was no such location will return null (for e.g if the phone is turned off) If the provider is currently disabled, null is returned
Getting a GPS fix takes time. onLocationChanged()
will be called only after getting a proper fix, this time may range from 20 seconds to a few minutes.
Only after onLocationChanged()
is called at least once, will getLastKnownLocation()
return the last valid location.
Upvotes: 2
Reputation: 30825
According to the documentation for getLastKnownLocation:
If the provider is currently disabled, null is returned.
So if you don't have GPS enabled on the device you're testing this on, you're going to get null. If you're using the android emulator, please see this stackoverflow post to see how to emulate a particular location.
Upvotes: 0