1

我想要的是在获得第一次位置更新并将其添加到领域后只获得一个新位置并删除位置更新,但面临的问题是有时在一次更新中获得超过 100 个位置并在领域崩溃应用程序中执行 100 个事务

public void getCurrentLocation(final Context context) {

    LocationRequest mLocationRequest;
    final LocationCallback mLocationCallback;
    final FusedLocationProviderClient mFusedLocationClient;
    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(context);
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(60000);
    mLocationRequest.setFastestInterval(60000);
    mLocationRequest.setNumUpdates(1);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }


    mLocationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult)
        {
            if (locationResult == null)
            {
                return;
            }
            mFusedLocationClient.removeLocationUpdates(this);

            Location tempLocation = locationResult.getLastLocation();
            if (locationResult.getLocations().size() > 0)
            {
                tempLocation = locationResult.getLocations().get(0);
            }
            if(tempLocation != null )
            {
                RealmManager.writeLocationInRealm(context, tempLocation, true, 0);
            }
        }
    };

    mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null);
}
4

2 回答 2

1

您可以通过以下代码实现此目的

此代码在 Kotlin 中

private var fusedLocationClient: FusedLocationProviderClient?=null

在你的 onCreate()

fusedLocationClient = LocationServices.getFusedLocationProviderClient(this@YourActivity)
        fusedLocationClient!!.lastLocation
                .addOnSuccessListener { location: Location? ->
                        //Your lattitude location!!.latitude
                        //Your Longitude location.longitude
                    }
于 2018-08-23T11:44:04.303 回答
0

我遇到了同样的问题,这就是我在 kotlin 中解决它的方法

fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)

        locationCallback = object : LocationCallback() {
            override fun onLocationResult(locationResult: LocationResult) {
                super.onLocationResult(locationResult)


                if (locationResult.lastLocation != null && locationResult.lastLocation.latitude > 0 && locationResult.lastLocation.longitude > 0) {

                    UserLocationObject.lastLocation = locationResult.lastLocation

                    fusedLocationClient.removeLocationUpdates(locationCallback)

                }
            }


}
于 2018-12-30T13:23:24.673 回答