Android:GPS位置无法正常工作

问题描述 投票:1回答:1

我试图检索位置如下:

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

android gps geolocation
1个回答
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;
                }
            }
        }
© www.soinside.com 2019 - 2024. All rights reserved.