Android Геозона стреляет только в фоновом режиме - PullRequest
0 голосов
/ 06 февраля 2020

Я пытаюсь создать обратный вызов, который прослушивает события, когда пользователь покидает определенную область. Код ниже является сборником учебного кода, который я скопировал из разных мест. Кроме того, я добавил все разрешения в свой манифест. Я запускаю это в эмуляторе и переключаю свое местоположение GPS вокруг. Проблема: я не получаю никаких обратных вызовов, если только не запущен Google-Maps.

  • Когда работает Google-Maps, я получаю все уведомления, как с моим приложением на переднем плане, так и в фоновом режиме ,
  • Если я убью Карты Google, у меня не будет никаких событий. Даже с requestBuilder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)

Что я тут не так делаю? Я пытался оставить свое приложение открытым в течение 5 минут (я прочитал, что время обновления по умолчанию составляет 3 минуты), и все равно получил 0 событий. Однако, если google-maps открыто, я немедленно получаю события, даже если мое приложение находится в фоновом режиме.

манифест:

...
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
     ...
    <application>
         ...
        <receiver android:name=".GeoFenceBroadcastReceiver"/>
    </application>


код:

import android.Manifest;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.pm.PackageManager;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingClient;
import com.google.android.gms.location.GeofencingRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;

import java.util.LinkedList;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

class GeoFencing {

    public CompletableFuture<Void> GeoTest(MainActivity parentActivity) {
        final CompletableFuture<Void> ret = new CompletableFuture<>();
        GeofencingClient geofencingClient = LocationServices.getGeofencingClient(parentActivity);
        LinkedList<Geofence> geofenceList = new LinkedList<>();
        String fenceID = "TestingFence";
        double latitude = ...;//not telling
        double longitude = ...;//not telling
        float radiusInMeters = 100;
        geofenceList.add(new Geofence.Builder()
                // Set the request ID of the geofence. This is a string to identify this
                // geofence.
                .setRequestId(fenceID)

                .setCircularRegion(
                        latitude,
                        longitude,
                        radiusInMeters
                )
                .setExpirationDuration(Geofence.NEVER_EXPIRE)
                .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
                        Geofence.GEOFENCE_TRANSITION_EXIT)
                .setNotificationResponsiveness(5_000)//5 seconds
                .build());

        //setup the first request:
        GeofencingRequest.Builder requestBuilder = new GeofencingRequest.Builder();
        requestBuilder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
        requestBuilder.addGeofences(geofenceList);
        GeofencingRequest geofencingRequest = requestBuilder.build();

        //register for events:
        // Reuse the PendingIntent if we already have it.
        Intent intent = new Intent(parentActivity, GeoFenceBroadcastReceiver.class);
        // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when
        // calling addGeofences() and removeGeofences().
        PendingIntent geofencePendingIntent = PendingIntent.getBroadcast(parentActivity, 0, intent, PendingIntent.
                FLAG_UPDATE_CURRENT);

        //Request background location runtime permission
        //If your app targets Android 10 or higher, you must also request the ACCESS_BACKGROUND_LOCATION runtime permission before you call addGeofences(). The logic needed to request the permission is shown in the following code snippet:
        if (ContextCompat.checkSelfPermission(parentActivity,
                Manifest.permission.ACCESS_BACKGROUND_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            final int background_location_permission_request_code=0x6766;
            ActivityCompat.requestPermissions(parentActivity,
                        new String[] { Manifest.permission.ACCESS_BACKGROUND_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION  },
                        background_location_permission_request_code);
        } else {
            // Background location runtime permission already granted.
            //Add geofences
            //To add geofences, use the GeofencingClient.addGeofences() method. Provide the GeofencingRequest object, and the PendingIntent. The following snippet demonstrates processing the results:
            geofencingClient.addGeofences(geofencingRequest, geofencePendingIntent)
                    .addOnSuccessListener(parentActivity, new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            ret.complete(null);
                        }
                    })
                    .addOnFailureListener(parentActivity, new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            ret.completeExceptionally(e);
                        }
                    });

        }


        return ret;
    }


}
...