why am i not reciving any logs or toast when user enters,dwells and exit the geofences radius

49 Views Asked by At

my goal is to show toast msg when user enters, dwells and exits the geofence This is my main class in Kotlin my goal is to show a toast message when the user comes in the geofence radius of Xmeters like toast for if he enters, dwells, and leaves that geofences so this is the main activity code
I'm Not able to receiving any toast or logs This is my code for main activity

fun geofencing(gMap: GoogleMap): List<Geofence> {
    val geofenceList = mutableListOf<Geofence>()

    val locations = listOf(
        GeofenceLocation(addlatitude, addlongitude, 20.0f),
    )

    for (location in locations) {
        geofenceList.add(
            Geofence.Builder()
                .setRequestId("GEO_KEY") // Use a unique ID for each geofence
                .setCircularRegion(
                    location.latitude,
                    location.longitude,
                    location.radius
                )
                .setLoiteringDelay(200)
                .setExpirationDuration(Geofence.NEVER_EXPIRE)
                .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER or Geofence.GEOFENCE_TRANSITION_EXIT)
                .build()
        )
        addGeofencesToMap(gMap,geofenceList)
    }

    return geofenceList
}

fun addGeofencesToMap(gMap: GoogleMap, geofences: List<Geofence>) {
    for (geofence in geofences) {
        val geofenceLocation = LatLng(geofence.latitude, geofence.longitude)
        val geofenceRadius = 20.0f

        // Add a circle around the geofence location
        val circleOptions = CircleOptions()
            .center(geofenceLocation)
            .radius(20.0)
            .strokeColor(this.resources.getColor(R.color.red))
            .fillColor(this.resources.getColor(R.color.blue))// Adjust the color and transparency as needed
        gMap.addCircle(circleOptions)

        // Add a marker at the geofence location
        val markerOptions = MarkerOptions()
            .position(geofenceLocation)
            .title("Geofence Marker")
        gMap.addMarker(markerOptions)
    }
}

private fun getGeofencingRequest(): GeofencingRequest {

    return GeofencingRequest.Builder().apply {
        setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER or GeofencingRequest.INITIAL_TRIGGER_EXIT)
        addGeofences(geofencing(gMap))
    }.build()
}

private val geofencePendingIntent: PendingIntent by lazy {
    val intent = Intent(this, GeofenceBroadcastReceiver::class.java)
    PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
}

private fun startGeofencing() {
    val geofencingRequest = getGeofencingRequest()
    val pendingIntent = geofencePendingIntent

    // Request geofence updates
    if (ActivityCompat.checkSelfPermission(
            this,
            Manifest.permission.ACCESS_FINE_LOCATION
        ) != PackageManager.PERMISSION_GRANTED
    ) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return
    }
    geofencingClient.addGeofences(geofencingRequest, pendingIntent)?.run {
        addOnSuccessListener {
            // Geofences were added successfully
            // You can log this or perform other actions
            Log.d("Geofence", "Geofences added successfully")
        }
        addOnFailureListener {
            // Geofences could not be added
            // You can log this or perform other error handling
            Log.e("Geofence", "Error adding geofences: ${it.message}")
        }
    }
}

data class GeofenceLocation(
    val latitude: Double,
    val longitude: Double,
    val radius: Float
)

And this is my brodcast class GeofenceBroadcastReceiver : BroadcastReceiver() {

companion object{
    private val TAG = "GeofenceReceiver"
}


override fun onReceive(context: Context?, intent: Intent?) {
    val geofencingEvent = intent?.let { GeofencingEvent.fromIntent(it) }

    if (geofencingEvent != null && !geofencingEvent.hasError()) {
        val geofenceTransition = geofencingEvent.geofenceTransition

        if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
            geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT
        ) {
            val triggeringGeofences = geofencingEvent.triggeringGeofences

            val geofenceTransitionDetails = triggeringGeofences?.let {
                getGeofenceTransitionDetails(
                    context,
                    geofenceTransition,
                    it
                )
            }

            if (geofenceTransitionDetails != null) {
                Log.i(TAG, geofenceTransitionDetails)
                Toast.makeText(context, geofenceTransitionDetails, Toast.LENGTH_SHORT).show()
            }
        } else {
            Log.e(TAG, "Unknown transition")
        }
    } else {
        Log.e(TAG, "Error handling geofence event")
    }
}

private fun getGeofenceTransitionDetails(
    context: Context?,
    geofenceTransition: Int,
    triggeringGeofences: List<Geofence>
): String {
    val geofenceTransitionString = when (geofenceTransition) {
        Geofence.GEOFENCE_TRANSITION_ENTER -> "Entered the geofence"
        Geofence.GEOFENCE_TRANSITION_EXIT -> "Exited the geofence"
        else -> "Unknown transition: $geofenceTransition"
    }

    val triggeringGeofencesIdsList = triggeringGeofences.map { it.requestId }
    return "$geofenceTransitionString: ${triggeringGeofencesIdsList.joinToString(", ")}"
}

}

0

There are 0 best solutions below