Use the LocationManager https://developer.android.com/reference/android/location/LocationManager.html.
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
致电给getLastKnownLocation()
不阻塞 - 这意味着它将返回null
如果当前没有空缺职位 - 那么您可能想看看通过LocationListener https://developer.android.com/reference/android/location/LocationListener.html to the requestLocationUpdates() method https://developer.android.com/reference/android/location/LocationManager.html#requestLocationUpdates(java.lang.String,%20long,%20float,%20android.app.PendingIntent)相反,这将为您提供位置的异步更新。
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
}
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
您需要为您的申请提供ACCESS_FINE_LOCATION允许 https://developer.android.com/reference/android/Manifest.permission.html#ACCESS_FINE_LOCATION如果你想使用GPS。
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
您可能还想添加ACCESS_COARSE_LOCATION允许 https://developer.android.com/reference/android/Manifest.permission.html#ACCESS_COARSE_LOCATION当 GPS 不可用时,请选择您的位置提供商getBestProvider() method https://developer.android.com/reference/android/location/LocationManager.html#getBestProvider(android.location.Criteria,%20boolean).