安卓地理围栏广播接收器

4
我使用GoogleApiClient实现了地理围栏 - > 当触发时,服务连接到GoogleApiClient并添加多个地理围栏。
在此之前,我已经注册了另一个IntentService作为地理围栏事件的“回调”。这个方法或多或少有效,但仅当应用程序在前台时才有效。因为我想在应用程序在后台/关闭时也接收地理围栏事件,所以我进行了一些搜索,并将回调从IntentService移动到BroadcastReceiver,但现在即使应用程序在前台也无法获取地理围栏事件。
我已经向互联网寻求解决方案(最常见的答案是:将事件监听器从Service更改为BroadCastReceiver - 但这使情况变得更糟)。
以下是我的设置:
清单:
    <receiver
        android:name=".service.GeofenceReceiver">
        <intent-filter>
            <action android:name="com.example.geofence.ACTION_RECEIVE" />
        </intent-filter>
    </receiver>

    <receiver android:name=".service.BootReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>

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

引导接收器:

public class BootReceiver extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {
      GeofenceRegistrationService.startService(context,true);
  }
}

地理围栏接收器:

public class GeofenceReceiver extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {

      Logger.e(this, "GeofenceReceiver called");

      GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);

      if (geofencingEvent.hasError()) {
          Logger.e(this, String.valueOf(geofencingEvent.getErrorCode()));

      } else {
        Logger.i(this, geofencingEvent.getTriggeringLocation().getLatitude() + ", " +geofencingEvent.getTriggeringLocation().getLongitude());

      }
  }
}

地理围栏注册服务:

public class GeofenceRegistrationService extends Service implements ConnectionCallbacks, OnConnectionFailedListener, ResultCallback<Status> {


  public static final String KEY_FORCE_CLEAN = "FORCE_CLEAN";

  public static void startService(Context context, boolean forceClean) {

      Intent intent = new Intent(context, GeofenceRegistrationService.class);

      intent.putExtra(KEY_FORCE_CLEAN, forceClean);

      context.startService(intent);

  }

  private GoogleApiClient mGoogleApiClient;
  private PendingIntent mGeofencePendingIntent;

  @Nullable
  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {

    if (isLocationPermissionGranted() && intent != null) {

        startGeofenceRegistration();

    } else {

        this.stopSelf(startId);

    }

    return START_REDELIVER_INTENT;
  }

  public void startGeofenceRegistration() {

    if (mGoogleApiClient == null) {
        mGoogleApiClient = buildAPIClient();
    }

    if (!mGoogleApiClient.isConnected() && !mGoogleApiClient.isConnecting()) {
        mGoogleApiClient.connect();
    } else {
        registerGeofences();
    }
  }


  private boolean isLocationPermissionGranted() {
    return ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
  }

  private synchronized GoogleApiClient buildAPIClient() {

    return new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

  }

  private void addGeoFences() {
    if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
        try {
            LocationServices.GeofencingApi.addGeofences(
                    mGoogleApiClient,
                    createGeofencesRequest(),
                    getGeofencePendingIntent()
            ).setResultCallback(this);
        } catch (SecurityException securityException) {
            Logger.e(this, securityException);
        }
    }
  }

  private void removeGeoFences() {
    if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
        try {
            LocationServices.GeofencingApi.removeGeofences(
                    mGoogleApiClient,
                    getGeofencePendingIntent()
            ).setResultCallback(this);
        } catch (SecurityException securityException) {
            Logger.e(this, securityException);
        }
    }
 }

 private PendingIntent getGeofencePendingIntent() {
    if (mGeofencePendingIntent != null) {
        return mGeofencePendingIntent;
    }
    //Intent intent = new Intent(this, GeofenceEventHandlingService.class);
    Intent intent = new Intent("com.example.geofence.ACTION_RECEIVE");
    mGeofencePendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    return mGeofencePendingIntent;
  }

  @Override
  public void onConnectionFailed(@NonNull ConnectionResult  connectionResult) {
    Logger.d(this, "CONNECTION_FAILED");
  }

  @Override
  public void onConnected(@Nullable Bundle bundle) {
    Logger.d(this, "CONNECTED");
    registerGeofences();

  }

  private void registerGeofences() {
    removeGeoFences();
    addGeoFences();
  }

  @Override
  public void onConnectionSuspended(int i) {
    Logger.d(this, "connection suspended");
  }

  private GeofencingRequest createGeofencesRequest() {
    GeofencingRequest.Builder builder = new GeofencingRequest.Builder();

    List<Poi> pois = Config.getPersistenceService().getPois();

    int counter = 0;
    for (Poi p : pois) {
        if (p.isCoordinateSet()) {
            Geofence fence = new Geofence.Builder()
                    .setRequestId(String.valueOf(p.getId()))
                    .setCircularRegion(p.getLat(), p.getLon(), 2500) // TODO
                    .setExpirationDuration(Geofence.NEVER_EXPIRE)
                    .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
                    .build();

            builder.addGeofence(fence);

            counter++;
        }
    }

    Logger.i(this, "added geofences: " + counter);

    return builder.build();
  }


  @Override
  public void onDestroy() {

    if (mGoogleApiClient != null && (mGoogleApiClient.isConnected() || mGoogleApiClient.isConnecting())) {
        mGoogleApiClient.disconnect();
    }

    super.onDestroy();
  }

  @Override
  public void onResult(@NonNull Status status) {
    if (status.isSuccess()) {
        Logger.d(this, "Geofences added");

    } else {
        Logger.d(this, "Failed to add geofences");
    }
  }


}

我做错了什么?我忽略了什么?
3个回答

3

以下是我已经让它工作的内容,但请注意,我在Activity中添加和删除我的地理围栏,并在IntentService中接收地理围栏过渡。

我认为您应该尝试构建您的Intent,指定new Intent(context, YourReceiverClass),并使用PendingIntent.getBroadcast()创建PendingIntent。虽然这是我使用的方式:

private PendingIntent getGeofencePendingIntent(){
    // Re-use the Pending Intent if it already exists
    if(mGeofencePendingIntent != null){
        return mGeofencePendingIntent;
    }

    // The intent for the IntentService to receive the transitions
    Intent intent = new Intent(getContext(), GeofenceTransitionsIntentService.class);

    // Create the pending intent
    mGeofencePendingIntent = PendingIntent
            .getService(getContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    return mGeofencePendingIntent;
}

在我的IntentService中:

@Override
protected void onHandleIntent(Intent intent) {
    GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
    if (geofencingEvent.hasError()) {
        String errorMessage = GeofenceErrorMessages.getErrorString(this,
                geofencingEvent.getErrorCode());
        Log.e(LOG_TAG, errorMessage);
        return;
    }

    // Get the transition type.
    int geofenceTransition = geofencingEvent.getGeofenceTransition();

    // Test that the reported transition was of interest.
    if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
            geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {

        // Get the geofences that were triggered. A single event can trigger multiple geofences.
        List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();

       // Do something with geofences

    }
}

1
搞定了 - 谢谢 Sammy。在更改所有可能的部分时,我忽略了 PendingIntent.getService(),实际上需要使用 PendingIntent.getBroadcast()。 - Thomas S.E.

2

其实我曾遇到类似问题,但我希望做的是相反的事情:从Service更改为Broadcast。在查看您的问题后,我注意到您之所以没有在Broadcast中收到geofence转换是因为在getPendingIntent方法中请求了一个Service。

private PendingIntent getGeofencePendingIntent() {
    (...)
    mGeofencePendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    (...)
  }

在我的情况下,我使用了getBroadcast,结果很好。
mGeofencePendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

希望这对你有所帮助。 祝好!

-1

在你发布的代码中,你的意图过滤器是错误的。

应该改为:

    <receiver
    android:name=".service.GeofenceReceiver">
    <intent-filter>
        <action android:name="com.example.geofence.ACTION_RECEIVE" />
    </intent-filter>
    </receiver>

你应该使用:

    <receiver
    android:name=".service.GeofenceReceiver">
    <intent-filter>
        <action android:name="com.example.geofence.ACTION_RECEIVE_GEOFENCE" />
    </intent-filter>
    </receiver>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接