Геопреградите не задействат моята услуга

Прочетох различни уроци, форуми и официалната документация на Google и все още не мога да разбера защо кодът ми не работи според очакванията. Има съответните части:

Дейност

public class MainMap extends FragmentActivity implements OnMarkerClickListener, OnMapReadyCallback,
        ConnectionCallbacks, OnConnectionFailedListener, LocationListener, ActivityCompat.OnRequestPermissionsResultCallback, ResultCallback<Status> {

    private static final int REQUEST_ACCESS_FINE_LOCATION = 0;
    protected GoogleApiClient mGoogleApiClient;
    protected Location mCurrentLocation;
    protected LocationRequest mLocationRequest;
    private GoogleMap m_map;
    private SupportMapFragment m_map_fragment;

    protected ArrayList<Geofence> mGeofenceList;
    private PendingIntent mGeofencePendingIntent;
    private boolean m_geofences_added;
    private SharedPreferences m_preferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_map);
        m_preferences = this.getSharedPreferences("com.example",Context.MODE_PRIVATE);
        // map fragment
        m_map_fragment= (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        m_map_fragment.getMapAsync(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        // location and geofences
        add_location_and_geofences();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onStop() {
        // remove geofences
        LocationServices.GeofencingApi.removeGeofences(mGoogleApiClient, getGeofencePendingIntent());
        super.onStop();
        mGoogleApiClient.disconnect();
    }

    @Override
    public void onConnected(Bundle connectionHint) {
        // permissions
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            request_fine_location_permission();
        }
        // location
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        // geofencing
        try {
            LocationServices.GeofencingApi.addGeofences(
                    mGoogleApiClient,
                    getGeofencingRequest(),
                    getGeofencePendingIntent()
            ).setResultCallback(this);
        } catch (SecurityException securityException) {
            Log.e(TAG, "Invalid location permission. " +
                    "You need to use ACCESS_FINE_LOCATION with geofences", securityException);
        }
    }

    public void onResult(Status status) {
        if (status.isSuccess()) {
        } else {
            String errorMessage = GeofenceErrorMessages.getErrorString(this,
                    status.getStatusCode());
            Log.e(TAG, errorMessage);
        }
    }

    private void add_location_and_geofences() {
        for (int i =0; i < 3; i++) {
            mGeofencePendingIntent = null;
            mGeofenceList = new ArrayList<>();
            mGeofenceList.add(new Geofence.Builder()
                    .setRequestId(Integer.toString(i)) // request id is the index so that I can later retrieve it
                    .setCircularRegion( /* I set coordinates here and a radius of 10meters*/)
                    .setExpirationDuration(NEVER_EXPIRE)
                    .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_DWELL)
                    .setLoiteringDelay(4000)
                    .build());
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
            mLocationRequest = new LocationRequest();
            mLocationRequest.setInterval(1000);
            mLocationRequest.setFastestInterval(500);
            mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        }
    }

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

    private GeofencingRequest getGeofencingRequest() {
        GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
        builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_DWELL);
        builder.addGeofences(mGeofenceList);
        return builder.build();
    }
}

моята услуга:

public class GeofenceTransitionsIntentService extends IntentService {

    private Intent m_intent;

    @Override
    public void onCreate() {
        super.onCreate();
        m_intent = new Intent(this, Guide.class);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
        if (geofencingEvent.hasError()) {
            String errorMessage = GeofenceErrorMessages.getErrorString(this,
                    geofencingEvent.getErrorCode());
            Log.e(TAG, errorMessage);
        } else {
            if (debug_mode) {
                Log.i(TAG, "something has been received");
            }
            int geofenceTransition = geofencingEvent.getGeofenceTransition();
            if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_DWELL) {
                List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();
                for (Geofence geofence : triggeringGeofences) {
                        Log.i(TAG, "INSIDE GEOFENCE");
                }
            } else {
                Log.e(TAG, getString(R.string.geofence_transition_invalid_type, geofenceTransition));
            }
        }
    }
}

и моят манифест

<service android:name="com.example.GeofenceTransitionsIntentService" />

С този код geofencing тихо се проваля - услугата ми никога не се задейства, както при използване на wifi на закрито, така и при използване на 3G/4G мрежи на открито.


person Marinos K    schedule 22.04.2017    source източник
comment
onLocationChanged изпълнява ли се?   -  person Kishore Jethava    schedule 22.04.2017
comment
да, получавам редовни актуализации   -  person Marinos K    schedule 22.04.2017
comment
След това трябва да добавите geofence вътре onLocationChanged   -  person Kishore Jethava    schedule 22.04.2017
comment
това няма ли да означава, че ще добавя няколко геозони всяка секунда?   -  person Marinos K    schedule 22.04.2017
comment
задайте ограничението на вашия setCircularRegion повече от 200 метра   -  person Murugan.P    schedule 12.06.2017


Отговори (1)


Търсите ли само събития за престой или събития за влизане и излизане? Ако е последното, задайте началния тригер на INITIAL_TRIGGER_ENTER, а типовете преходи на GEOFENCE_TRANSITION_ENTER| GEOFENCE_TRANSITION_EXIT.

Ако търсите събития на задържане, трябва да останете в геозоната за около 5 минути, за да получите първоначалното задействане. Когато напуснете, няма да получите никакво събитие за него, но след като го въведете отново, ще трябва да останете в рамките на вашата геозона отново за още 5 минути, за да получите вашето събитие.

person Pablo Baxter    schedule 24.04.2017
comment
Хей @Pablo Baxter. Трябва ли да зададете първоначалния тригер като Enter AND Dwell, за да бъде задействано събитието? Имам само Dwell set и забавяне от 1000ms и просто не се задейства. Чакам вече 15 минути. По подразбиране Enter и Dwell са зададени - така че се чудя дали е задължително. Благодаря. - person Rhonage; 04.07.2018