【问题标题】:Android: GPS Location not workingAndroid:GPS定位不工作
【发布时间】:2015-05-04 15:27:52
【问题描述】:

我正在尝试按如下方式检索位置:

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) Maps 应用程序时 - 它会正确显示位置,甚至会显示通知图标(看起来像感叹号)。

还有一个 GPS 坐标应用程序 - 它也显示为空白。

我已在手机上打开“设置”>“位置”。如果重要的话,这是 Android 4.4.4 Sony Experia 手机。

【问题讨论】:

标签: android gps geolocation


【解决方案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;
                }
            }
        }

【讨论】:

  • 那么......谷歌地图和其他一些依赖位置的应用程序如何在同一部手机上运行?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-22
相关资源
最近更新 更多