Android Geofencing не срабатывает на некоторых мобильных устройствах, таких как OnePlus, Xiaomi и т. Д. - PullRequest
0 голосов
/ 05 декабря 2018

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

Проблемы в Xiaomi & OnePlus Мобильный.

  1. В Xiaomi 5A Некоторое время Ввод работает нормально, но Выход не запускается.
  2. В Xiaomi Poco f1 Оба Ввод и Выход не работают.
  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);

        }

    }
}

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

1 Ответ

0 голосов
/ 14 февраля 2019

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

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

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

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

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

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

Также вы можете проверить эти Проблемы с геозонами

...