在Android中使用“仅设备”获取用户位置

时间:2019-02-26 17:22:23

标签: java gps location android-gps fusedlocationproviderclient

上下文:

我一直在使用FusedLocationProviderClient来获取用户的位置。 当手机处于“高精度”模式时,一切都会按预期进行。 但是,并非所有电话都具有很高的准确性。 因此,我该如何仅通过GPS来获取用户位置

到目前为止,我已经尝试过:

1-通过FusedLocationProviderClient进行了尝试:

 providerClient = LocationServices.getFusedLocationProviderClient(this);

locationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult);
                Log.e(TAG,"CALLBACK RECEIVED");
                processNewLocation(locationResult.getLastLocation());
            }
        };

locationRequest = new LocationRequest();
locationRequest.setInterval(LocationConstant.UPDATE_INTERVAL_IN_MILLISECONDS);
locationRequest.setFastestInterval(LocationConstant.FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

providerClient.requestLocationUpdates(locationRequest,
                    locationCallback, Looper.myLooper());

位置仅在设备中时,位置回调不会被调用,但如果它具有很高的精度,它会完美地工作(也将setPriority()更改为每个优先级并且没有运气)。

2-使用位置管理器对此进行了尝试:

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new MyLocationListener());
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new MyLocationListener());
locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, new MyLocationListener());

 private class MyLocationListener implements LocationListener {

        public void onLocationChanged(Location location) {
            String message = String.format(
                    "New Location \n Longitude: %1$s \n Latitude: %2$s",
                    location.getLongitude(), location.getLatitude()
            );
            Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
        }

        public void onStatusChanged(String s, int i, Bundle b) {
            Toast.makeText(MainActivity.this, "Provider status changed",
                    Toast.LENGTH_LONG).show();
        }

        public void onProviderDisabled(String s) {
            Toast.makeText(MainActivity.this,
                    "Provider disabled by the user. GPS turned off",
                    Toast.LENGTH_LONG).show();
        }

        public void onProviderEnabled(String s) {
            Toast.makeText(MainActivity.this,
                    "Provider enabled by the user. GPS turned on",
                    Toast.LENGTH_LONG).show();
        }

    }

结果仍然相同

0 个答案:

没有答案