GEOFENCE_NOT_AVAIBLE (код 1000) при попытке настроить геозону - PullRequest
0 голосов
/ 01 января 2019

Проблема возникает на Android старше Oreo, а также на Oreo и новее.

Не удается настроить работу геозон, даже если выполнены следующие шаги:

  • Установлены службы определения местоположениявысокая точность
  • Wi-Fi и мобильные данные включены
  • Приложению предоставлены разрешения на определение местоположения
  • Службы Google добавлены в проект
  • Службы Google иPlay Store обновлен и установлен на устройстве
  • Отключена оптимизация батареи (цель тестирования)

Я проверил следующий код, если GPS_PROVIDER и NETWORK_PROVIDERenabled:

@Override
protected void onResume() {
    super.onResume();
    LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
        Log.e("Provider", "Provider is not avaible");
    } else if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
        Log.v("Provider", "GPS Provider is avaible");
    }
    if (!manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
        Log.e("Network Provider", "Provider is not avaible");
    } else if (manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
        Log.v("Network Provider", "provider is avaible");
    }

}

Оба эти параметра дали мне положительный результат, поэтому проблема не может быть здесь.

Точная ошибка:

E / Geofence: com.google.android.gms.common.api.ApiException: 1000:

Я установил mGeofencingClient в начале onCreate:

  @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mGeofencingClient = LocationServices.getGeofencingClient(getApplicationContext());

Я установил геозоны сследующий код:

            mGeofenceList.add(
                    new Geofence.Builder()
                            .setRequestId("blablabla")
                            .setCircularRegion(50.32, 43.23, 232)
                            .setExpirationDuration(-1L)
                            .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
                                    Geofence.GEOFENCE_TRANSITION_EXIT)
                            .build());

//        }
        PermissionCheck mPermissionCheck = new PermissionCheck();
        if (!mPermissionCheck.isPermissionGranted(getApplicationContext())){
            mPermissionCheck.askForPermission(MainActivity.this);
            return;
        }
        setGeofences();


    }

private GeofencingRequest getGeofencingRequest(){
    if (mGeofenceList.isEmpty()){
        return null;}
    Log.v("mGeofenceList", mGeofenceList.toString());
    GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
    builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER |
                                GeofencingRequest.INITIAL_TRIGGER_EXIT);
    builder.addGeofences(mGeofenceList);
    return builder.build();
}

private PendingIntent getGeofencePendingIntent(){
    if (mGeofencePendingIntent != null){
        return mGeofencePendingIntent;
    }
    Intent intent = new Intent(getApplicationContext(), Geofencing.class);
    mGeofencePendingIntent =  PendingIntent.getService(getApplication(),
            0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    return mGeofencePendingIntent;
}

@SuppressLint("MissingPermission")
private void setGeofences(){
    GeofencingRequest geofencingRequest = getGeofencingRequest();
    PendingIntent pi = getGeofencePendingIntent();
    mGeofencingClient.addGeofences(geofencingRequest, pi)
        .addOnSuccessListener(MainActivity.this, new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Log.d("Geofences", "geofencing set up succesfully");
                Toast.makeText(MainActivity.this, "Geofences set up", Toast.LENGTH_SHORT).show();

            }
        })
        .addOnFailureListener(MainActivity.this, new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.e("Geofence", e.toString());
            LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
                Log.e("Provider", "Provider is not avaible");
            }
            if (!manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
                Log.e("Network Provider", "Provider is not avaible");
            }

        }
    });
}

Этот код почти такой же, как из Google DocumentaТион.Разрешение на манифест:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-feature android:name="android.hardware.location.network"/>
    <uses-feature android:name="android.hardware.location.gps"/>

Gradle:

implementation 'com.google.android.gms:play-services-maps:16.0.0'
implementation 'com.google.android.gms:play-services-location:16.0.0'

Кто-нибудь может увидеть ошибку, которую я мог совершить?Заранее спасибо!

1 Ответ

0 голосов
/ 01 января 2019

ОК, это минимальная рабочая программа для геозон, основанная на вашем OP - просто чтобы исключить реализацию вашего кода - есть пара других интерфейсов, реализованных для других тестов, поэтому игнорируйте.

«Работа» означает, что она успешно добавляетthe geofence.:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, LocationListener, ActivityCompat.OnRequestPermissionsResultCallback {

    private List<Geofence> mGeofenceList = new ArrayList<>();

    private GeofencingClient gfc;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        gfc = LocationServices.getGeofencingClient(getApplicationContext());

        mGeofenceList.add(new Geofence.Builder().setRequestId("aa").setCircularRegion(50.32, 43.23, 232).setExpirationDuration(-1L).setTransitionTypes(
                Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT).build());


        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            // Check Permissions Now
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    1);
        }

        else {
            setGeofences();
        }

    }


    private GeofencingRequest getGeofencingRequest(){
        if (mGeofenceList.isEmpty()){
            return null;}
        Log.v("mGeofenceList", mGeofenceList.toString());
        GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
        builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER |
                GeofencingRequest.INITIAL_TRIGGER_EXIT);
        builder.addGeofences(mGeofenceList);
        return builder.build();
    }

    private PendingIntent mGeofencePendingIntent;

    private PendingIntent getGeofencePendingIntent(){
        if (mGeofencePendingIntent != null){
            return mGeofencePendingIntent;
        }
        Intent intent = new Intent(getApplicationContext(), Object.class);
        mGeofencePendingIntent =  PendingIntent.getService(getApplication(),
                0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        return mGeofencePendingIntent;
    }

    @SuppressLint("MissingPermission")
    private void setGeofences(){
        GeofencingRequest geofencingRequest = getGeofencingRequest();
        PendingIntent pi = getGeofencePendingIntent();
        gfc.addGeofences(geofencingRequest, pi)
                .addOnSuccessListener(this, new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Log.d("Geofences", "geofencing set up succesfully");
                        Toast.makeText(MapsActivity.this, "Geofences set up", Toast.LENGTH_SHORT).show();

                    }
                })
                .addOnFailureListener(MapsActivity.this, new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.e("Geofence", e.toString());
                        LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
                            Log.e("Provider", "Provider is not avaible");
                        }
                        if (!manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
                            Log.e("Network Provider", "Provider is not avaible");
                        }

                    }
                });
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        setGeofences();

    }

}

После некоторого исследования я обнаружил, что могу воссоздать код ошибки 1000 с этим примером кода.Он основан на этом сообщении на форуме: https://androidforums.com/threads/error-adding-geofence-on-android-8.1289302/

Таким образом, чтобы следовать этим указаниям (чтобы исправить - но я перевернул их, чтобы воссоздать, а затем исправить):

Использовать телефон "Настройки| Безопасность и местоположение | Местоположение | Режим »- переключайтесь между« Высокая точность, Экономия батареи или Только устройство », пока не получите это приглашение (путь настроек будет зависеть от сборки Android):

enter image description here

В этом примере кода - если вы ответите «DISAGREE», пример кода сгенерирует код ошибки 1000;если вы повторите и ответите «СОГЛАСОВАНО», то добавление геозоны будет успешным.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...