android - 背景地理围栏真的适用于 Android 8+ 吗?

标签 android location android-8.0-oreo geofencing android-geofence

我有一个地理围栏应用程序,我正尝试将其移植到 Android 8+ 上。我读过 tutorial关于这个主题,并切换到使用 compile 'com.google.android.gms:play-services-location:16.0.0'

当应用程序不在前台时,地理围栏进入事件永远不会触发。我等待的时间超过了文档所说的两分钟。我已经等了 15 分钟,但没有结果。只要我将应用程序带到地理围栏内的前台,它就会立即触发。

我知道在 Android 8+ 上对后台服务有限制,但谷歌的教程说要使用在 Android 8+ 上应该被阻止的 IntentService。 后见之明编辑:上述教程绝对错误。不要跟随它。 IntentService 将不起作用。

我尝试关注 this answer ,它说使用新的 GeofencingClient 来设置您的 Intent 来解决这个问题。 (我不明白为什么这会有帮助,因为它仍然使用 IntentService 来接收事件,并且它在我的代码中不起作用。)

这个对相关问题的回答 here建议您必须使用 BroadcastReceiver 而不是 IntentService,但我不明白为什么这会有所不同,因为 Android 8 在后台对 BroadcastReceivers 施加了与 IntentServices 相同的限制。 事后编辑:这个链接的答案也是正确的。虽然隐式 BroadcastReceivers 受到限制,但在运行时注册以向特定包发送请求的显式 BroadcastReceivers 不受限制并且可以正常工作。

是否真的有可能在 Android 8+ 上获得在后台唤醒您的应用程序的地理围栏回调?如果是这样,您如何才能做到这一点?

我的地理围栏设置:

googleApiClient = new GoogleApiClient.Builder(this.context)
        .addApi(LocationServices.API)
        .addConnectionCallbacks(getServiceSetup())
        .addOnConnectionFailedListener(getServiceFailureStrategy())
        .build();
geofencingClient = LocationServices.getGeofencingClient(context);

Intent intent =  new Intent(context, mIntentService);
// We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when
// calling addGeofences() and removeGeofences().
geofencePendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.
            FLAG_UPDATE_CURRENT);

geofencingClient.addGeofences(geofences, geofencePendingIntent)
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                 @Override
                   public void onSuccess(Void aVoid) {
                     getAddGeofencesCallback(runnable, geofencesToAdd).onResult(new Status(0));
                     Log.e(TAG, "Successfully added geofences with GeofencingClient");
                   }
                 })
                .addOnFailureListener(new OnFailureListener() {
                   @Override
                   public void onFailure(Exception e) {
                     getAddGeofencesCallback(runnable, geofencesToAdd).onResult(new Status(1));
                     Log.e(TAG, "Failed to add geofences with GeofencingClient", e);

Intent 服务:

public class GeofenceService extends IntentService {
    private static final String TAG = "GeofenceService";

    public GeofenceService() {
        super(TAG);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        GeofenceTransition transition = GeofenceServiceManager.getGeofenceTransition(intent);
        if (transition == null) {
            return;
        }

        GeofenceServiceManager.logd(
                TAG,
                "onHandleIntent. geofence: " +
                        GeofenceMessage.notificationTitleFor(this, transition)
        );
        processErrors(transition);
        sendBroadcast(transition);
    }

    private Intent generateBroadcast(GeofenceTransition transition) {
        Intent broadcastIntent = new Intent();

        broadcastIntent.addCategory(GeofenceUtils.CATEGORY_GEOFENCE_SERVICES)
                       .setAction(GeofenceUtils.actionNameFor(transition))
                       .putStringArrayListExtra(
                               GeofenceUtils.GEOFENCE_IDS,
                               new ArrayList<String>(transition.getIds())
                                               );

        return broadcastIntent;
    }

    private void sendBroadcast(GeofenceTransition transition) {
        if (transition.isError() || transition.unknownType()) {
            GeofenceServiceManager.logd(TAG, "geofence transition is error or unknown type.");
            return;
        }

        broadcastManager().sendBroadcast(generateBroadcast(transition));
    }

    private LocalBroadcastManager broadcastManager() {
        return LocalBroadcastManager.getInstance(this);
    }

    private void processErrors(GeofenceTransition transition) {
        if (!transition.isError()) {
            return;
        }

        Log.e(TAG, "geofence error: "+GeofenceMessage.errorDetailsFor(this, transition));

        Intent broadcastIntent = generateBroadcast(transition);
        broadcastIntent.putExtra(
                GeofenceUtils.GEOFENCE_STATUS,
                GeofenceMessage.errorMessageFor(this, transition)
                                );
        broadcastManager().sendBroadcast(broadcastIntent);
    }
}

AndroidManifest.xml:

...
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

      <service
          android:name=".geofence.GeofenceService"
          android:enabled="true"
          android:exported="false">
      </service>
...

编辑 1: 根据 Google 记录的对 Android 8+ 后台处理的限制,这在我看来是不可能的。 Android 8+ 会在进入后台后 10 分钟内杀死正在运行的应用程序,并在不在前台时阻止启动服务,包括 Intent 服务。然而谷歌说:

Note: On Android 8.0 (API level 26) and higher, if an app is running in the background while monitoring a geofence, then the device responds to geofencing events every couple of minutes. To learn how to adapt your app to these response limits, see Background Location Limits.

鉴于已记录的后台执行限制,这怎么可能?

编辑 2:我已经看到 list 中声明的​​ BroadcastReceiver 可以使用 Intent 交付的蓝牙 LE 检测将应用程序启动到 Android 8+ 的后台。该代码如下所示:

Intent intent = new Intent();
intent.setComponent(new ComponentName(context.getPackageName(), "com.example.MyBroadcastReceiver"));
<receiver android:name="com.example.MyBroadcastReceiver">
         </receiver>

这确实适用于 BLE 检测以将应用程序启动到后台。如果传送到 BroadcastReceiver,系统发起的 Intent 是否会以某种方式不受 Android 8+ 后台执行限制的影响(以 IntentServices 没有的方式)?如果是这样,这是否适用于地理围栏? (剧透警报:是的,它会!阅读下面接受的答案。)

最佳答案

你需要替换:

geofencePendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.
            FLAG_UPDATE_CURRENT); 

Intent intent = new Intent(this, GeofenceBroadcastReceiver.class); 
mGeofencePendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

为了支持 Android 8,由于 Background Execution Limits,您应该使用 BroadcastReceiver 来接收地理围栏 Intent (服务不能在后台运行)

查看更多详细信息:https://github.com/android/location-samples/commit/5f83047c8a462d7c619f6275b624e219b4622322

google 示例如何使用地理围栏:https://github.com/googlesamples/android-play-location/tree/master/Geofencing

关于android - 背景地理围栏真的适用于 Android 8+ 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54949978/

相关文章:

android - 如何在 Android O 中动态更改通知声音

android - 如果我无限期地在后台运行 Android 线程会发生什么

android - 获取位置 android Kotlin

android - getLastKnownLocation 不适用于 Samsung Galaxy S3 4.0.4

android - 如何在 Android Oreo 中管理来自未知来源的安装?

java - 找不到封闭方法 'void lambda$getTestFlowable$0(io.reactivex.FlowableEmitter)'

android - 通过USB从Windows PC与android设备通信

android - 在 ViewPager 中同步 fragment 滚动

android - 有什么优化的方法可以在 android 中呈现大列表吗?

objective-c - 没有位置服务的 iOS 后台轮询