无法通过GPS获取位置:安卓



我是安卓新手。我正在尝试使用 GPS 获取我的位置。我已经包括了权限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>

每当我尝试使用getLastKnownLocationLocationManager获取Location时,我都会得到空对象。此外,GPS 已启用。这是我的代码:

LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Location location;
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
    Log.d("ManualLog", "GPS_DISABLED");
    Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(settingsIntent);
} else {
    Log.d("ManualLog", "GPS_ENABLED");
    location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}

locationManager.getLastKnownLocation 如果 GPS 还没有时间进行修复,将返回 null。Android 不提供"立即提供位置信息"方法。当GPS得到修复后,onLocationChanged()将运行。它是事件驱动的,你必须耐心等待那个事件。一旦 onLocationChanged() 运行,getLastKnownLocation() 将返回一个非空值。

您是否在模拟器或设备上运行它?如果在模拟器上,您可能需要通过"模拟器控制"手动将 GPS 数据发送到模拟器。在 eclipse 中,您可以在 Window>Open Perspective>DDMS 中找到它。

如果您在设备上运行,您的设备以前是否可能从未收到过 GPS 信号?

尝试将最后一行替换为:

List<String> providers = locationManager.getProviders(true);
if(!providers.isEmpty()) {
    location = locationManager.getLastKnownLocation(providers.get(0));
} else {
   Log.d("ManualLog", "No provider");
}

最新更新