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

dav*_*ung 4 android location geofencing android-geofence android-8.0-oreo

我有一个地理围栏应用程序,我正在尝试移植它以在 Android 8+ 上工作。我已阅读有关该主题的教程,并切换到使用compile 'com.google.android.gms:play-services-location:16.0.0'.

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

我知道在 Android 8+ 上对后台服务有限制,但 Google 的教程说使用 IntentService 应该在 Android 8+ 上被阻止。 事后编辑:上述教程是完全错误的。不要跟着它。IntentService 将不起作用。

我尝试按照这个答案,它说使用新的GeofencingClient来设置你的意图来解决这个问题。(我不明白为什么这会有所帮助,因为它仍然使用 IntentService 来接收事件,并且在我的代码中不起作用。)

This answer to a related question here表明您必须使用BroadcastReceiver而不是IntentService,但我不明白为什么这会有所作为,因为Android 8在后台对BroadcastReceiver施加了与IntentServices相同的限制。 事后编辑:这个链接的答案也是正确的。虽然隐式广播接收器受到限制,但在运行时注册以将请求发送到特定包的显式广播接收器不受限制并且可以正常工作。

是否真的有可能在 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);
Run Code Online (Sandbox Code Playgroud)

意向服务:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

AndroidManifest.xml:

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

      <service
          android:name=".geofence.GeofenceService"
          android:enabled="true"
          android:exported="false">
      </service>
...
Run Code Online (Sandbox Code Playgroud)

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

注意:在 Android 8.0(API 级别 26)及更高版本上,如果应用程序在监控地理围栏时在后台运行,则设备每隔几分钟就会响应地理围栏事件。要了解如何使您的应用适应这些响应限制,请参阅后台位置限制。

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

编辑 2:我看到清单中声明的​​ BroadcastReceiver 使用意图提供的蓝牙 LE 检测在 Android 8+ 上将应用程序启动到后台工作。该代码如下所示:

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

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

phn*_*mnn 5

你需要更换:

geofencePendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.
            FLAG_UPDATE_CURRENT); 
Run Code Online (Sandbox Code Playgroud)

Intent intent = new Intent(this, GeofenceBroadcastReceiver.class); 
mGeofencePendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Run Code Online (Sandbox Code Playgroud)

为了支持 Android 8,您应该使用 BroadcastReceiver 来接收地理围栏意图,由于后台执行限制(服务不能在后台运行)

详情请参阅:https : //github.com/googlesamples/android-play-location/commit/5f83047c8a462d7c619f6275b624e219b4622322

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