地理位置服务需要时间来获得经度和纬度

时间:2018-03-14 10:57:27

标签: android

我正在开发一个应用程序获取用户的位置并将其发送到数据库。我的问题是,当用户打开活动时,地理位置大约需要一分钟才能获得经度和纬度。有没有办法立即获得位置

我的代码

  @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);


    if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)  == PackageManager.PERMISSION_GRANTED){
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,0, locationListener);
        }
    }
}

   private void latAndLong(final String modelSelected, final String email, final String likelyProblem){
    ActivityCompat.requestPermissions(LocationActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
    GeoLocation geoLocation = new GeoLocation(getApplicationContext());
    Location l = geoLocation.getLocation();
    if (l != null){
        double lat = l.getLatitude();
        double lng = l.getLongitude();
        Toast.makeText(getApplicationContext(), "Lat: " + lat + "\n Lon: " + lng, Toast.LENGTH_LONG).show();
        LocationSender locationSender = new LocationSender(lat, lng, email, modelSelected, likelyProblem);
        sendNetworkRequest(locationSender);
    }

    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    locationListener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };
    if (Build.VERSION.SDK_INT < 23){
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
    }else{

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)  != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        }else{
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我不确定为什么要使用GeoLocation来获得简单的纬度和经度。据我所知,GeoLocation旨在将地址转换为GPS坐标,或者相反。它的工作原理是向Google地方信息服务器发出请求,因此会出现网络延迟,并且还会受到一些使用限制。

快速获取位置的最佳方法是使用Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider); 获取初始位置。 之后的任何位置更新都会触发onLocationChanged(Location location)的{​​{1}}方法。编写自定义逻辑可以帮助您跟踪更多位置更改。

Android开发者网站有一个很棒的article describing the best strategies for using the location services。这可能是关于在Android上使用位置服务的最新,最全面的文章,所以我建议阅读本文。