【发布时间】:2013-06-13 15:45:48
【问题描述】:
为什么我的位置变量的值为空?我正在正确设置我的 LocationManager。
这是我的源代码:
//Get the current location
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
myCriteria = new Criteria();
String provider = locationManager.getBestProvider(myCriteria, true);
Location location = locationManager.getLastKnownLocation(provider);
boolean isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
//Location location;
if (isGpsEnabled) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
else {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
Log.i(TAG, "Provider is: "+provider);
Log.i(TAG, "Location is: "+location);
这是 logcat 的输出:
06-17 10:40:52.637: D/dalvikvm(15106): GC_FOR_ALLOC freed 534K, 7% free 10586K/11360K, paused 16ms, total 16ms
06-17 10:40:52.677: I/OGT.RideTracking(15106): Provider is: gps
06-17 10:40:52.677: I/OGT.RideTracking(15106): Location is: null
06-17 10:40:52.677: D/AndroidRuntime(15106): Shutting down VM
我的代码有什么问题?
【问题讨论】:
-
不保证
getLastKnownLocation为您提供位置。如果是null,您应该调用locationManager.requestLocationUpdates()并等待提供者获取位置。 -
您是否设置了 ACCESS_FINE_LOCATION 和 ACCESS_COARSE_LOCATION 权限?
-
是的,我在 Manifest 文件中确实拥有这些权限
-
您可能会得到空值,因为当前没有 lastKnownLocation。打开谷歌地图或使用 GPS 的东西,它可能会工作
标签: android android-location android-maps-v2