Одежда для Android: геозона — ApiException: 1000

Я создаю приложение Android для Android Wear. Для экономии заряда батареи я пытаюсь использовать геозоны, чтобы отслеживать, входите ли вы в какое-либо место или выходите из него. Но я не могу заставить его работать.

Во-первых, я не уверен, поддерживаются ли геозоны на Android Wear? (Отдельно?) У меня есть часы Huawei watch 2 LTE с GPS-антенной, и у меня уже работает FusedLocationClient, поэтому я знаю, что GPS работает. Мой код для геозон работает. телефон без проблем.

Когда я запускаю код, я получаю следующее исключение:

com.google.android.gms.common.api.ApiException: 1000:

В документации Google API я обнаружил, что это означает: GEOFENCE_NOT_AVAILABLE, что не дает мне никакой дополнительной информации.

Это сервис, который я написал для запуска и создания геозоны:

public class GeofencingService extends Service implements OnSuccessListener, OnFailureListener {

    private static final String TAG = "GeofencingService";
    private static final int NOTIFICATION_ID = 1;

    private GeofencingClient mGeofencingClient;
    private List<Geofence> mGeofenceList;
    private NotificationManager mNotificationManager;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        mGeofencingClient = LocationServices.getGeofencingClient(this);
        mGeofenceList = new ArrayList<>();
        createGeofences();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        showNofification();
        setupGeofence();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mNotificationManager.cancel(NOTIFICATION_ID);
    }

    private PendingIntent getGeofencePendingIntent()
    {
        Intent intent = new Intent(this, GeofenceBroadcastReceiver.class);
        return PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }

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

        // The INITIAL_TRIGGER_ENTER flag indicates that geofencing service should trigger a
        // GEOFENCE_TRANSITION_ENTER notification when the geofence is added and if the device
        // is already inside that geofence.
        builder.setInitialTrigger(INITIAL_TRIGGER_ENTER | INITIAL_TRIGGER_EXIT);

        // Add the geofences to be monitored by geofencing service.
        builder.addGeofences(mGeofenceList);

        // Return a GeofencingRequest.
        return builder.build();
    }

    private void setupGeofence()
    {
        try{
            Log.i(TAG, "Setting up geofences...");
            mGeofencingClient.addGeofences(getGeofencingRequest(), getGeofencePendingIntent()).addOnSuccessListener(this).addOnFailureListener(this);
        } catch (SecurityException ex)
        {
            Log.d(TAG, "Exception: " + ex.getMessage());
        }
    }

    private void createGeofences()
    {
        Log.i(TAG, "Creating geofence...");
        mGeofenceList.add(new Geofence.Builder()
                // Set the request ID of the geofence. This is a string to identify this
                // geofence.
                .setRequestId("Test1")
                // Set the circular region of this geofence.
                .setCircularRegion(
                        50.03535,
                        4.33139,
                        100
                )
                .setExpirationDuration(NEVER_EXPIRE)
                // Set the transition types of interest. Alerts are only generated for these
                // transition. We track entry and exit transitions in this sample.
                .setTransitionTypes(GEOFENCE_TRANSITION_ENTER | GEOFENCE_TRANSITION_EXIT)
                // Create the geofence.
                .build());
    }

    private void showNofification()
    {
        Intent appIntent = new Intent(this, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, appIntent, 0);

        Notification notification = new NotificationCompat.Builder(this, NotificationCompat.CATEGORY_SERVICE)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(getText(R.string.location_service_title))
                .setContentText(getText(R.string.location_service_text))
                .setLocalOnly(true)
                .setOngoing(true)
                .setContentIntent(contentIntent)
                .build();

        mNotificationManager.notify(NOTIFICATION_ID, notification);
    }

    @Override
    public void onFailure(@NonNull Exception e) {
        Log.d(TAG, "Exception: " + e.getMessage());
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                setupGeofence();
            }
        }, 2000);
    }

    @Override
    public void onSuccess(Object o) {
        Log.d(TAG, "Success!");
    }
}

Вот также ссылка github на пример, который я написал.

Надеюсь, кто-нибудь поможет мне разобраться в этом, потому что я уже перепробовал все, что знаю :)


person kevingoos    schedule 12.01.2018    source источник
comment
Что означает 1000?   -  person greenapps    schedule 12.01.2018
comment
@greenapps Как я нашел на этом сайте: developers.google .com/android/reference/com/google/android/gms/ означает: GEOFENCE_NOT_AVAILABLE   -  person kevingoos    schedule 12.01.2018
comment
В порядке. Тогда, пожалуйста, прокомментируйте.   -  person greenapps    schedule 12.01.2018
comment
@greenapps Это просто исключение. Нет решения?   -  person kevingoos    schedule 12.01.2018
comment
Это не комментарий. Вы должны прокомментировать сообщение о том, что геозона недоступна. Какой вывод?   -  person greenapps    schedule 12.01.2018
comment
Вы можете проверить этот связанный сообщение SO. Не все устройства Wear имеют оборудование для поддержки этого, хотя LG Urbane 2 имеет LTE, и довольно много устройств Wear поддерживают Wi-Fi. Он должен быть сопряжен с портативным устройством, чтобы использовать геозону, как указано в сообщении SO. Надеюсь это поможет.   -  person Mr.Rebot    schedule 16.01.2018
comment
@Mr.Rebot Мои часы (Huawei Watch 2 LTE) имеют GPS, LTE, Wi-Fi, ... Они подключены к телефону, но это не помогает.   -  person kevingoos    schedule 16.01.2018
comment
@kevingoos есть новости по этому поводу? Я также столкнулся с той же проблемой.   -  person Numair    schedule 22.10.2018


Ответы (2)


Когда вы читаете документацию и видите, что код ошибки соответствует GEOFENCE_NOT_AVAILABLE, плюс согласно комментарию @Mr.Rebot:

«Не все носимые устройства имеют аппаратное обеспечение для поддержки [...]»

Вы можете предположить, что GEOFENCE НЕДОСТУПНА на вашем устройстве Huawei watch 2.

Вы также можете обратиться в службу поддержки Huawei напрямую, чтобы получить подтверждение.

person A STEFANI    schedule 22.01.2018
comment
поддержка хуавей просто ужас - person Vyacheslav; 22.01.2018

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

person Khemraj Sharma    schedule 15.07.2020