我正在尝试按如下方式检索位置:
LocationManager locationManager = (LocationManager)MyApp.getAppContext().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
// Getting the name of the provider that meets the criteria
String provider = locationManager.getBestProvider(criteria, false);
if(provider!=null && !provider.equals("")){
// NOTE: the location below is null !!
Location location = locationManager.getLastKnownLocation(provider);
String lat = location.getLatitude();
String lng = location.getLongitude();
}
上面的“位置”为空。为什么?
但是,当我打开(Google)地图应用时,它会正确显示位置,甚至会显示通知图标(看起来像感叹号)。
并且有一个GPS坐标应用程序 - 它也显示空白。
我已启用设置>手机上的“位置”。如果重要的话,这是Android 4.4.4 Sony Experia手机。
答案 0 :(得分:1)
好吧,如果GPS工作正常,您似乎没有正确检查。你应该这样做的方式:
final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if (!manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
//GPS is not enabled !!
}
您还可以创建一个AlertDialog,以便用户知道GPS未启用,您可以通过这样做将他发送到GPS设置:
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
在此之后,我实现了一个位置监听器并获取坐标,这是一个例子,检查出来
How do I get the current GPS location programmatically in Android?
更新:他们可能会通过其他提供商获取坐标(通常是那时工作得更好的人)。因此,如果GPS不起作用,只需尝试其他提供商,这里有一个例子:
Location lastKnownLocation = null;
List<String> providers = null;
if(locationManager != null) providers = locationManager.getAllProviders();
if(providers != null)
{
for(int i=0; i<providers.size(); i++)
{
if(locationManager != null) lastKnownLocation = locationManager.getLastKnownLocation(providers.get(i));
if(lastKnownLocation != null)
{
position = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
break;
}
}
}