【问题标题】:Android GPS is returning null locationAndroid GPS正在返回空位置
【发布时间】:2017-06-04 21:59:24
【问题描述】:

我已经编写了代码,如果 GPS 被禁用,它将由代码启用并尝试从 gps 获取位置,但我得到一个空值。下面是我的代码

   public void getValue() {
    LocationManager mlocManager = (LocationManager) MySettings.this.getSystemService(Context.LOCATION_SERVICE);
    boolean gpsEnabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    System.out.println("GPS IS "+gpsEnabled);
    if (!gpsEnabled) {
        String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

        if (!provider.contains("gps")) { // if gps is disabled
            final Intent poke = new Intent();
            poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
            poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
            poke.setData(Uri.parse("3"));
            sendBroadcast(poke);
        }
    }
    SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy");
    try {
        getBatteryLevel();
        mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, MySettings.this);
        Location location = mlocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        mLocation = location;
        if (location != null) {
            lat = location.getLatitude();
            lon = location.getLongitude();
            address = getAddress();
            alt = location.getAltitude();
            if (meterFootFlag) {
                diameter = location.getAccuracy();
            } else
                diameter = location.getAccuracy() / 3.28084;
        } else {
            lat = 0.0;
            lon = 0.0;
            alt = 0.0;
        }

    } catch (Exception e) {
        lat = 0.0;
        lon = 0.0;
        alt = 0.0;
    }

我还在清单文件中添加了权限

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

但我得到的位置为空值。

关于如何获取位置的任何想法?

【问题讨论】:

标签: android gps


【解决方案1】:

您的代码是正确的,只需等待 GP 从卫星获取高度,这可能需要 1 分钟以上。

【讨论】:

    【解决方案2】:

    尝试:

        public Location showLocation(){
        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //Class model, save latitude and longitude
        NavegadorCoordenadas locate = new NavegadorCoordenadas();
        Criteria crit = new Criteria();
        crit.setAccuracy(Criteria.ACCURACY_FINE);
        String provider = lm.getBestProvider(crit, false);
        Location loc = getLastKnownLocation(lm);                    
        locate.setLatitude(loc.getLatitude()); 
        locate.setLongitude(loc.getLongitude());
        return loc;     
    }
    
    private Location getLastKnownLocation(LocationManager location) {
        List<String> providers = location.getProviders(true);
        Location bestLocation = null;
        for (String provider : providers) {
            Location l = location.getLastKnownLocation(provider);           
            if (l == null) {
                continue;
            }
            if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {             
                bestLocation = l;
            }
        }
        if (bestLocation == null) {
            return null;
        }
        return bestLocation;
    }
    

    【讨论】:

      【解决方案3】:

      确保您只检查DEVICE。在模拟器中,它会为GPS 提供空值,因为它正在系统中运行,因此它没有GPS 的权限

      【讨论】:

        【解决方案4】:
        locationMangaer = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        
                String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
                if(!provider.contains("gps")){ //if gps is disabled
                    final Intent poke = new Intent();
                    poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
                    poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
                    poke.setData(Uri.parse("3")); 
                    sendBroadcast(poke);
                }
        
            locationListener = new MyLocationListener();
            locationMangaer.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, 10,
                    locationListener);
        

        现在在同一活动中创建 MyLocationListener 类

        private class MyLocationListener implements LocationListener {
            @Override
            public void onLocationChanged(Location loc) {
        
                    String longitude = "Longitude: " +loc.getLongitude();  
                    String latitude = "Latitude: " +loc.getLatitude();
        
                    /*----------to get City-Name from coordinates ------------- */
                    String cityName=null;                 
                    Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());                  
                    List<Address>  addresses;  
                    try {  
                     addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);  
                     if (addresses.size() > 0) { 
                      System.out.println(addresses.get(0).getLocality());  
                     cityName=addresses.get(0).getLocality();  
                        System.out.println("MESSAGE:"+cityName);
                     }
                    } catch (IOException e) {                 
                     e.printStackTrace();  
                    } 
        
                    String s = longitude+"\n"+latitude+"\t city name:"+cityName;
                        Log.v("OUTPUT, s);
            }
        
            @Override
            public void onProviderDisabled(String provider) {
                // TODO Auto-generated method stub          
            }
        
            @Override
            public void onProviderEnabled(String provider) {
                // TODO Auto-generated method stub          
            }
        
            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
                // TODO Auto-generated method stub          
            }
        }
        

        实际设备中运行您的应用程序。

        您可以弄清楚自动启动 GPS 并查看 console logcat。

        【讨论】:

          【解决方案5】:

          确保通过 设置--> 应用程序-->YourApp--> 权限 另一个原因可能是延迟,连接网络需要时间,有时超过一分钟

          【讨论】:

            猜你喜欢
            • 2013-01-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-03-24
            • 2016-11-13
            相关资源
            最近更新 更多