如何在点击时获得 Android 中的精确 GPS 位置

How to get exact GPS position in Android on click

我正在尝试通过单击按钮获得准确的 GPS 位置。我正在使用 fusesLocationProviderClient 并拥有 FINE_LOCATION 权限。

private void getCurrentGPSLocation() {
   // get the new location from the fused client
   // update the UI - i.e. set all properties in their associated text view items

   //Initialize new location request
        LocationRequest locationRequest = new LocationRequest()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(10000)
                .setFastestInterval(1000)
                .setNumUpdates(1);
  //Initialize location call back
        LocationCallback locationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                //Initialize location1
                Location location1 = locationResult.getLastLocation();
   //Set Accuracy
            double accura1 = location1.getAccuracy();}
};
        //Request location updates
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        fusedLocationProviderClient.requestLocationUpdates(locationRequest
                , locationCallback, Looper.myLooper());
    }

然后我从 location1 变量中获取坐标,因为我从中获取了精度。问题是这非常不精确,因为我得到的精度为 800-1000m。打开 GoogleMaps 几秒钟后返回到我的应用程序调用 getLastLocation();使用另一个按钮(不是我的代码示例的一部分),我得到了 4-5 米的精度。再次使用我的代码时,精度再次为 800-1000m。 所以我的问题是,如何更改我的代码以在我的 getCurrentGLSLpcation() 方法中获得这种准确性。

我正在使用此代码获取位置,使用 FusedLocationProviderClient 并给出几乎准确的位置高达 5..7 米

try {
   
        Task<Location> locationResult = mFusedLocationClient.getLastLocation();
        locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>() {
            @Override
            public void onComplete(@NonNull Task<Location> task) {
                if (task.isSuccessful()) {
                  Location  location = task.getResult();
                    if (location != null) {
                        
                        //fo your job
                        
                    } else {
                        Toast.makeText(context, "Please on GPS", Toast.LENGTH_SHORT).show();
                    }
                }
                else {
                    Toast.makeText(context, "error:"+task.getException().getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    
} catch (SecurityException e) {
    Log.e("Exception: %s", e.getMessage(), e);
}

在尝试了您的想法后,我找到了解决方案:

 private void getCurrentGPSLocation() {
        // get the new location from the fused client
        // update the UI - i.e. set all properties in their associated text view items

        //Initialize new location request
        LocationRequest locationRequest = new LocationRequest()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(2500)
                .setFastestInterval(2000)
                .setNumUpdates(8);

        //Initialize location call back
        LocationCallback locationCallback = new LocationCallback() {
            @Override

            public void onLocationResult(LocationResult locationResult) {
                //Initialize location1
                Location location1 = locationResult.getLastLocation();
                //Set latitude
                tvLatitude.setText(String.valueOf(location1.getLatitude()));
                //Set longitude
                tvLongitude.setText(String.valueOf(location1.getLongitude()));
                //Set Accuracy
                double accura1 = location1.getAccuracy();
                tvAccuracy.setText(new DecimalFormat("##.##").format(accura1) + " m");
                //Set Altitude
                double altit1 = location1.getAltitude();
                tvAltitude.setText(new DecimalFormat("##.##").format(altit1) + " m");

                //Get Adress
                double longitude1 = location1.getLongitude();
                double latitude1 = location1.getLatitude();
                Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
                try {
                    List<Address> listAddresses = geocoder.getFromLocation(latitude1, longitude1, 1);
                    if (null != listAddresses && listAddresses.size() > 0) {
                        String _Location1 = listAddresses.get(0).getAddressLine(0);
                        //Set Location
                        tvLocation.setText(String.valueOf(_Location1));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                //Set Update Time
                TextView textView = findViewById(R.id.tv_update);
                SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy 'um ' HH:mm:ss z");
                String currentDateandTime = sdf.format(new Date());
                textView.setText(currentDateandTime);


            }

        };
        //Call method to insert data into database
        (new Handler()).postDelayed(this::OnReg, 30000);
        //OnReg();
        //Call Method to save data in SharedPreferences
        (new Handler()).postDelayed(this::saveData, 30000);
        //saveData();
        //call Method to save data in Internal File
        (new Handler()).postDelayed(this::saveToFile, 30000);
        //saveToFile();
        //Request location updates
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        fusedLocationProviderClient.requestLocationUpdates(locationRequest
                , locationCallback, Looper.myLooper());
    }

这是完整的代码,其中包含从该位置更新的文本视图。基本上我有 8 个位置更新,然后再获取最后一个也是最精确的位置来调用我的方法,这些方法将位置保存在数据库 (OnReg)、内部文件 (saveToFile) 和 SharedPreferences(saveData) 中。延迟 30 秒调用这些方法以确保位置准确。