How to find out why GPS coordinates are missing in Android?

偶尔善良 提交于 2019-12-02 15:59:06

问题


I am trying to get a device's location information using GPS, but for some reason one of the two coordinates is missing sometimes.

This is the code:

LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Log.d("LOCATION1", "Longitude: " + longitude);
Log.d("LOCATION2", "Latitude: " + latitude);

Sometimes I do get both coordinates, but not always, which makes me think about some kind of delay somewhere. Is there a way to find out why a GPS coordinate is missing when this happens?


回答1:


Because the GPS isn't always on. getLastKnownLocation will return a location if it knows one and if it isn't too stale. Since nothing else was using the GPS, it doesn't know one. If you need a location, either requestLocationUpdates or requestSingleUpdate, which will turn on the GPS and get a new location.




回答2:


 Criteria criteria = new Criteria();
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
   // mMap.addMarker(new MarkerOptions().position(sydney2).title("fi"));
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    locationManager.requestLocationUpdates(locationManager.getBestProvider(criteria, true), 2000, 0, new android.location.LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
           // 
        }

in onLocationChanged method you can use location.getLatitude & location.getLongitude



来源:https://stackoverflow.com/questions/35841573/how-to-find-out-why-gps-coordinates-are-missing-in-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!