繁体   English   中英

Android:GPS位置无法正常工作

[英]Android: GPS Location not working

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

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手机。

好吧,看来您没有正确检查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));

之后,我将实现一个位置侦听器并获取坐标,这是一个示例,请检查一下

如何在Android中以编程方式获取当前GPS位置?

更新:他们可能正在通过其他提供者(通常是那时候工作得更好的提供者)获取坐标。 因此,如果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;
                }
            }
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM