gpt4 book ai didi

android - 根据当前位置和某个位置之间的距离更改 LocationRequest 的间隔

转载 作者:行者123 更新时间:2023-11-29 01:38:41 29 4
gpt4 key购买 nike

我想通过使用 Fused Location API 更改更新间隔来节省电量。越远的地方,间隔越大。

public class service extends Service implements GooglePlayServicesClient.ConnectionCallbacks,GooglePlayServicesClient.OnConnectionFailedListener,LocationListener {
private LocationRequest locationrequest;
private LocationClient locationclient;



@Override
public void onCreate() {

int resp = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resp == ConnectionResult.SUCCESS) {
locationclient = new LocationClient(this, this, this);
locationclient.connect();
} else {
Toast.makeText(this, "Google Play Service Error " + resp, Toast.LENGTH_LONG).show();

}

}



@Override
public void onDestroy() {
super.onDestroy();
if(locationclient!=null)
locationclient.disconnect();
}

@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "onConnected");
if (locationclient != null && locationclient.isConnected()) {
locationrequest = LocationRequest.create();
locationrequest.setInterval(5000);
locationrequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationclient.requestLocationUpdates(locationrequest, this);

}
}

@Override
public void onDisconnected() {
Log.i(TAG, "onDisconnected");


}

@Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "onConnectionFailed");


}

@Override
public void onLocationChanged(Location location) {
if(location!=null){
double Lat=-34.922611;
double Lng = 138.596161;
Location Loc = new Location("");
Loc.setLatitude(Lat);
Loc.setLongitude(Lng);
Float dist=location.distanceTo(Loc);
String distance = Float.toString(dist);
if (dist>100){
Log.i("distance",distance);
locationclient.removeLocationUpdates(this);
locationrequest.setInterval(30000);
locationrequest.setPriority(LocationRequest.PRIORITY_LOW_POWER);
locationclient.requestLocationUpdates(locationrequest, this);

}

Log.i(TAG, "Location Request :" + location.getLatitude() + "," + location.getLongitude());


}

}
}

不幸的是,这不起作用..有人知道为什么吗?或者有更好的方法吗?谢谢

编辑 1:我得到的输出是一个 locationrequest,它在更改之前以相同的方式运行。如果我调用 locationrequest.getInterval ,将显示新的时间间隔,但 locationrequest 会给我更新第一个时间间隔。

最佳答案

使用 Fused Location API,您可以执行以下操作:

mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(INTERVAL)
.setFastestInterval(FASTEST_INTERVAL);

然后,当您的应用程序中触发事件并且您想要更改间隔时,您将调用同一段代码,但只需更改 INTERVALFASTEST_INTERVAL 值.更改它们后,不要忘记像这样更新位置更新:

LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

关于android - 根据当前位置和某个位置之间的距离更改 LocationRequest 的间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26258806/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com