How to get current location on android
Hey guys i want to get the latitude and longitude of the users location. I have tried developers site and stack overflow , there are loads of examples targeted on the moving user which use some thing like :- onLocationChanged() I dont need updates of the location , the user will just open i开发者_JS百科t for a minute or two so i need to find the location the time the application starts and what if the user has never used any geolocation app before hence i would also like an alternative for LocationManager.getLastKnownLocation()
My code is :-
LocationManager lm = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
// connect to the GPS location service
Location loc = lm.getLastKnownLocation(lm.NETWORK_PROVIDER);
Toast.makeText(currentLocation.this, "Latitude -> "+Double.toString(loc.getLatitude())
+" Longitude is -> "+Double.toString(loc.getLongitude()), Toast.LENGTH_LONG).show();
and is working fine. But i am scared that the getLastKnownLocation may return null when used for first time.
Thanks
Sign up for location updates and once you receive the first update, you can unregister for future updates.
In other words, create a LocationListener
and register it with your LocationManager
's requestLocationUpdates
method. In the onLocationChanged
method of your LocationListener
, call the removeUpdates
method on your LocationManager
, with this
as parameter.
It might take some time before you get a new location, but except for using getLastKnownLocation
there's not really an alternative.
精彩评论