我想通过使用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会给我第一个间隔的更新。
你应该解释你的代码是如何失败的:到底发生了什么,以及如何从您的期望有所不同。 – 2014-10-08 14:06:54
@WoodrowBarlow现在怎么样?谢谢 – maligno 2014-10-09 13:05:54