我正在尝试获取位置更新并将其发送到挂起的意图,我已经有这项工作了。但是有一个按钮,当按下它时,我希望它停止获取位置更新,这是我的代码:
主活动
public class MainActivity extends Activity implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
GoogleApiClient mGoogleClient;
PendingIntent pendingIntent;
LocationRequest locationRequest;
LocationServices locationServices;
...
protected void onStart() {
super.onStart();
mGoogleClient.connect();
}
@Override
protected void onStop() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleClient, pendingIntent);
super.onStop();
}
@Override
public void onLocationChanged(Location location) {
// this callback is invoked when location updates
}
@Override
public void onConnected(Bundle connectionHint) {
try {
locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setFastestInterval(30000)
.setInterval(60000);
pendingIntent = PendingIntent.getService(this, 0,
new Intent(this, MyLocationHandler.class),
PendingIntent.FLAG_UPDATE_CURRENT);
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleClient, locationRequest, pendingIntent);
//Toast.makeText(this, "Adding Toast", Toast.LENGTH_LONG).show();
} catch (Exception e) {
...
}
}
@Override
public void onConnectionSuspended(int cause) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// this callback will be invoked when the connection attempt fails
if (connectionResult.hasResolution()) {
// Google Play services can fix the issue
// e.g. the user needs to enable it, updates to latest version
// or the user needs to grant permissions to it
try {
connectionResult.startResolutionForResult(this, 0);
} catch (IntentSender.SendIntentException e) {
// it happens if the resolution intent has been canceled,
// or is no longer able to execute the request
}
} else {
// Google Play services has no idea how to fix the issue
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGoogleClient = new GoogleApiClient.Builder(this, this, this)
.addApi(LocationServices.API)
.build();
TrackBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
bTrack = !bTrack;
CheckTrack();
}
}
});
}
...
public void CheckTrack() {
if (a == null) {
a = tracker.getLocation();
}
if (bTrack) {
mGoogleClient.connect();
} else {
DisconnectHandlerCheck.postDelayed(DisconnectRunnableCheck, 500); }
}
}
Handler DisconnectHandlerCheck = new Handler();
Runnable DisconnectRunnableCheck = new Runnable() {
@Override
public void run() {
try {
onStop();
} catch (Exception e) {
...
}
}
};
}
出于某种原因,即使在我断开 Google 客户端并删除更新后,代码也会继续调用 PendingIntent。
为什么是想法?
断开 mGoogleClient 的连接后,使用 pendingIntent.cancel() 取消挂起的意图。它对我有用。
尝试使用 :mGoogleClient.disconnect();在你的 onStop()/method版本中。