Android 不会阻止 GPS 意图

Android won't stop GPS intent

我想询问 GPS 位置,即使应用程序处于后台。因此我使用了一个 PendingIntent 如下:

final Intent intent = new Intent(this, LocationReceiver.class);
mLocationIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mLocationIntent);

效果很好。但是,即使 MainActivity 被销毁,GPS 位置仍在更新。 Intent Service 不会停止。我试图像这样在 MainActivity 的 onDestroyed 方法中停止 Intent:

@Override
protected void onDestroy() {
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mLocationIntent);
}

...但是不会调用此方法。

如何在 MainActivity 被销毁时停止 Intent?

当您按下设备的主页按钮或后退按钮时,'ondestroy()' 方法不会立即被调用。根据 android 的文档,这是 在你的 activity 被摧毁之前你收到的最后一个电话。这可能是因为 activity 正在完成(有人在其上调用了 finish() ,或者因为系统正在临时销毁 activity 的这个实例以保存 space...。一个建议是在 'onPause()' 方法中停止 GPS 更新。像这样的东西:

@Override
protected void onPause() {
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mLocationIntent);
}

如果您想这样做,您需要为用户提供打开和关闭它的方法。

如果您使用 PendingIntent 注册 GPS 更新,这意味着即使不是 运行,您的应用也将获得 GPS 更新。这就是它的设计目的。即使 documentation 对此也很清楚:

This method is suited for the background use cases, more specifically for receiving location updates, even when the app has been killed by the system.

如果您只想在您的应用 运行 时获取 GPS 更新,那么您应该使用使用回调或侦听器的其他 requestLocationUpdates() 变体之一。如果您的应用被终止,这些变体将停止获取更新。