我想要的是只获取一个新位置,并在第一次更新位置并将其添加到领域后删除位置更新,但是面临的问题是有时一次更新会获得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);
}
答案 0 :(得分:0)
您可以通过以下代码实现
此代码在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
}
答案 1 :(得分: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)
}
}
}