我想通過使用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