Android Geofencing не запускается на некоторых мобильных устройствах, таких как OnePlus, Xiaomi и т. д.

Я использую код геозоны в соответствии с рекомендациями документа Android. Протестировано на реальных устройствах, таких как Sony XA1, Samsung J7 Nxt, Xiaomi 5A, Poco f1, OnePlus 6. Гео-зоны Enter и Exit работают правильно в Sony XA1, Samsung J7 Далее.

Проблемы в Xiaomi и OnePlus Mobile.

  1. В Xiaomi 5A иногда Enter работает правильно, но Exit не срабатывает.
  2. В Xiaomi Poco f1 оба Enter и Exit не работают.
  3. В OnePlus Mobile работает только при открытом приложении.

Код геозоны:

private GeofencingClient mGeofencingClient;
private ArrayList<Geofence> mGeofenceList;
private PendingIntent mGeofencePendingIntent;

mGeofenceList = new ArrayList<>();
mGeofencingClient = LocationServices.getGeofencingClient(getApplicationContext());

//Latitude & Longitude Comes from Array to Add
mGeofenceList.add(new Geofence.Builder().setRequestId(String.valueOf(mall.mallId)).setCircularRegion(
              mall.latitude,
              mall.longitude,
              mall.geofencingMeters)
             .setExpirationDuration(Geofence.NEVER_EXPIRE)
             .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
             .build());

private GeofencingRequest getGeofencingRequest() {

    GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
    builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
    builder.addGeofences(mGeofenceList);

    return builder.build();
}

private PendingIntent getGeofencePendingIntent() {
    if (mGeofencePendingIntent != null) {
        return mGeofencePendingIntent;
    }
    Intent intent = new Intent(this, GeofenceBroadcastReceiver.class);
    mGeofencePendingIntent = PendingIntent.getBroadcast(this, FENCING_REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    return mGeofencePendingIntent;
}

BroadcastReceiver

public class GeofenceBroadcastReceiver extends BroadcastReceiver {

    /**
     * Receives incoming intents.
     *
     * @param context the application context.
     * @param intent  sent by Location Services. This Intent is provided to Location
     *                Services (inside a PendingIntent) when addGeofences() is called.
     */
    @Override
    public void onReceive(Context context, Intent intent) {
        // Enqueues a JobIntentService passing the context and intent as parameters
        StoreFencing.enqueueWork(context, intent);
    }
  }
}

Служба ограждения:

public class StoreFencing extends JobIntentService {

    private static final int JOB_ID = 502;
    List<Geofence> triggeringGeofences;

    public static void enqueueWork(Context context, Intent intent) {
        enqueueWork(context, StoreFencing.class, JOB_ID, intent);
    }

    @Override
    protected void onHandleWork(@NonNull Intent intent) {

        GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
        if (geofencingEvent.hasError()) {

            return;
        }

        int geofenceTransition = geofencingEvent.getGeofenceTransition();

        if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER) {

            triggeringGeofences = geofencingEvent.getTriggeringGeofences();
            getGeofenceEnterTransitionDetails(triggeringGeofences);

        }

        if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {

            triggeringGeofences = geofencingEvent.getTriggeringGeofences();
            getGeofenceExitTransitionDetails(triggeringGeofences);

        }

    }
}

Есть ли проблема в коде или устройстве. Сообщите пользователям, чтобы они включили дополнительные настройки в этих мобильных устройствах. Помогите решить эту проблему.


person Yugesh    schedule 05.12.2018    source источник


Ответы (2)


Да, я тоже столкнулся с этими проблемами.

  1. На устройствах One Plus оптимизация батареи для вашего приложения должна быть отключена, т. е. для нее должно быть установлено значение «Не оптимизировать» в меню «Настройки» > «Аккумулятор» > «Все приложения» > «YourApp». Только тогда он будет работать, когда ваше приложение находится в фоновом режиме или даже не в фоновом режиме.

  2. На устройствах Xiaomi ваше приложение должно иметь разрешение на автоматический запуск в настройках, чтобы геозона работала правильно.

  3. Большинство других китайских устройств, таких как Lenovo, Coolpad и т. д., также не запускают никаких событий перехода через геозону после того, как приложение было убито из недавних.

Вы можете перенаправить пользователя на определенную страницу в настройках и попросить его включить/отключить их, чтобы геозона работала правильно.

Кроме этого я не нашел никакого решения.

Также вы можете проверить эти Устранение неполадок Geofence.

person Ashwin    schedule 14.02.2019

Избегайте использования широковещательных приемников, так как они являются целями для оптимизации батареи от Oreo и выше. Поэтому рекомендуется использовать fusedLocationProvider. Кроме того, вместо вызова Geofencing API лучше использовать формулу Haversine (используется для расчета расстояния между координатами).

LatLng Home = new LatLng(10.398152, 76.096864);
int Radius =100;
        fusedLocationProviderClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
                    @Override
                    public void onSuccess(Location location) {
                        //Haversine formula
        
                        double longitude = location.getLongitude() - Home.longitude;
                        double latitude  = location.getLatitude() - Home.latitude;
                        double a = Math.pow(Math.sin(latitude/2),2) + Math.cos(Home.latitude)
                                *Math.cos(location.getLatitude())*Math.pow(Math.sin(longitude/2),2);
                        double circuit = 2 * Math.asin(Math.sqrt(a));
                        double eradius = 6371;
                       if(circuit*eradius<Radius){
                           Log.e("User Status","Within Geofence");
                           
                                                  }
    else{
    Log.e("User Status","User outside Geofence");
    }
person Omjelo    schedule 04.02.2021