Alert Geofence once when map is opened

0

My geofence is trigering actions once when i open map. Basically i want it to show a toast and make a button visible once i enter a circle and show a toast and make a button invisible once i leave the circle. I can't find a solution so maybe you guys can help. Here's my code:

public class MapActivity extends AppCompatActivity implements OnMapReadyCallback, Geofence {

@Override
public void onMapReady(GoogleMap googleMap) {
    Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
    Log.d(TAG, "onMapReady: Map is ready");
    mMap = googleMap;
    if (mLocationPermissionsGranted) {
        try {
            boolean success = googleMap.setMapStyle(
                    MapStyleOptions.loadRawResourceStyle(
                            this, R.raw.mapstyle));

            if (!success) {
                Log.e(TAG, "Style parsing failed.");
            }
        } catch (Resources.NotFoundException e) {
            Log.e(TAG, "Can't find style. Error: ", e);
        }

        getDeviceLocation();

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        mMap.setMyLocationEnabled(true);


    }
    for (LatLng latLng : InfoArea) {
        mMap.addCircle(new CircleOptions()
                .center(latLng)
                .radius(5)
                .strokeColor(0xffff0000)
                .fillColor(0x44ff0000)
                .strokeWidth(1));
    }
    Geofencesetup(); //calling geofence setup
}

private static final String TAG = "MapActivity";

private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int PERMISSION_CODE = 1234;
private static final float DEFAULT_ZOOM = 15f;
//vars
private Boolean mLocationPermissionsGranted = false;
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
private List<LatLng> InfoArea;
private String GEOFENCE_KEY = "451";
PendingIntent pendingIntent;
GeofencingClient geofencingClient;
Button infobut;

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

    getLocationPermission();

    pendingIntent = PendingIntent.getBroadcast(this,0,
            new Intent(".ACTION_RECEIVE_GEOFENCE"),PendingIntent.FLAG_UPDATE_CURRENT);
    geofencingClient = LocationServices.getGeofencingClient(this);

    infobut = findViewById(R.id.Speak);
}

private void getDeviceLocation() {
    Log.d(TAG, "getDeviceLocation: getting the current location");

    mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
    try {
        if (mLocationPermissionsGranted) {
            final Task location = mFusedLocationProviderClient.getLastLocation();
            location.addOnCompleteListener(new OnCompleteListener() {
                @Override
                public void onComplete(@NonNull Task task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "onComplete: found location!");
                        final Location currentLocation = (Location) task.getResult();

                        moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),
                                DEFAULT_ZOOM);
                    } else {
                        Log.d(TAG, "onComplete: current location is null");
                        Toast.makeText(MapActivity.this, "unable to get current location", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    } catch (SecurityException e) {
        Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage());
    }
}

private void moveCamera(LatLng latLng, float zoom) {
    Log.d(TAG, "moveCamera: moving camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude);
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}

private void initMap() {
    Log.d(TAG, "initMap: initializing map");
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

    mapFragment.getMapAsync(MapActivity.this);

    initArea();
}

private void initArea() {
    InfoArea = new ArrayList<>();
    InfoArea.add(new LatLng(54.021410, 23.954885));
}

private void Geofencesetup(){ //Part of the problem
    Geofence.Builder geofencecreator = new Geofence.Builder();
    geofencecreator.setRequestId(GEOFENCE_KEY);
    geofencecreator.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT);
    geofencecreator.setCircularRegion(54.021410, 23.954885, 10); //latlng and radius of the circle
    geofencecreator.setExpirationDuration(Geofence.NEVER_EXPIRE);

    GeofencingRequest.Builder geoBuilder = new GeofencingRequest.Builder();
    geoBuilder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER | GeofencingRequest.INITIAL_TRIGGER_EXIT);
    geoBuilder.addGeofence(geofencecreator.build());

    Task task = geofencingClient.addGeofences(geoBuilder.build(), pendingIntent);

    task.addOnSuccessListener(new OnSuccessListener() {
        @Override
        public void onSuccess(Object o) {
            Log.i(TAG,"You're inside the zone");
            activityinsidecircleMaker();
        }
    });
    task.addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.i(TAG,"You're outside the zone");
            activityoutsidecircleMaker();
        }
    });
} //................................................................................
private void activityinsidecircleMaker(){ //the toast and the button i want it to show when user is inside a circle
    Toast.makeText(this,"You're inside a circle",Toast.LENGTH_SHORT).show();
    infobut.setVisibility(View.VISIBLE);
}
private void activityoutsidecircleMaker(){ //the toast and the button i want it to show when user is outside a circle(in this case button should become invisible)
    Toast.makeText(this,"You are now outside the circle",Toast.LENGTH_SHORT).show();
    infobut.setVisibility(View.INVISIBLE);
}//.............................................................................................

private void getLocationPermission() {
    Log.d(TAG, "getLocationPermission: getting location permissions");
    String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION};

    if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
            FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
                COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            mLocationPermissionsGranted = true;
            initMap();
        } else {
            ActivityCompat.requestPermissions(this,
                    permissions,
                    PERMISSION_CODE);
        }
    } else {
        ActivityCompat.requestPermissions(this,
                permissions,
                PERMISSION_CODE);
    }
}

@Override
public String getRequestId() {
    return null;
}

The actions that i want my program to do when user is inside or outside the circle are marked like this: //......... , so you guys could see it better. Also i think that is where the problem actually is i just can't find a way to solve it

java
android
google-maps
geofencing
asked on Stack Overflow May 6, 2020 by codingcodes

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0