0

I have an app that defines a Geofence location in an Activity called SearchSchool. I then implemented a BroadCastReceiver extension in another class to listen when user enters the geolocation and when he leaves it. I seem to have done everything correctly except the part where am supposed to send a notification to user from the BroadcastReceiverClass to the SearchSchool Activity which is an extension of AppCompatActivity class. Here is the code in the SearchSchool activity that defines the Geofence builder...

public class Search_School extends AppCompatActivity {

  PendingIntent geofencePendingIntent;
    private GeofencingClient geofencingClient;
    List<Geofence> geofences = new ArrayList<>();
    //replace with real latitude and longitude of your geofence
     //define the longitude and latitude of the geofence and radius
    private double lat = 37.8136;
    double lon = 74.0060;
    private float radius = 100;
    private long EXPIRATION_TIME = 10000;
    
     @Override
     protected void OnCreate(Bundle savedInstanceState){
    geofencingClient = LocationServices.getGeofencingClient(this);
        geofences.add(new Geofence.Builder()
                .setRequestId("MyGeofence")
                .setCircularRegion(lat, lon, radius)
                .setExpirationDuration(EXPIRATION_TIME).
                        setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
                .build());

        //add a geofence to the client
       geofencingClient.addGeofences(getGeofencingRequest(), getGeofencePendingIntent())
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Toast.makeText(getActivity(), "Geofence added with success",Toast.LENGTH_LONG).show();
                    }
                }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                 Toast.makeText(getActivity(),"Geofence addtion failed",Toast.LENGTH_LONG).show();
            }
        });
        }
    //create a  geofence request
   private GeofencingRequest getGeofencingRequest() {
        GeofencingRequest.Builder builder =new GeofencingRequest.Builder();
        builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
        builder.addGeofences(geofences);
        return builder.build();
    }
     //Create a geofence pendingRequest
           private PendingIntent getGeofencePendingIntent() {
            // Reuse the PendingIntent if we already have it.
            if (geofencePendingIntent != null) {
                return geofencePendingIntent;
            }
            Intent intent = new Intent(this, GeofenceBroadcastReceiver.class);
            // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when
            // calling addGeofences() and removeGeofences().
            geofencePendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.
                    FLAG_UPDATE_CURRENT);
            return geofencePendingIntent;
        }

}

Here is the BroadCastReeceiver class for detecting when user has entered the geofence and should send a notification to SearchSchoolactivity when it occurs

package com.example.fastuniforms;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofenceStatusCodes;
import com.google.android.gms.location.GeofencingEvent;

import java.util.List;

import static android.content.ContentValues.TAG;

public class GeofenceBroadcastReceiver extends BroadcastReceiver {
    // ...
    public void onReceive(Context context, Intent intent) {
        GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
        if (geofencingEvent.hasError()) {
            String errorMessage = GeofenceStatusCodes
                    .getStatusCodeString(geofencingEvent.getErrorCode());
            Log.e(TAG, errorMessage);
            return;
        }

        // Get the transition type.
        int geofenceTransition = geofencingEvent.getGeofenceTransition();

        // Test that the reported transition was of interest.
        if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
                geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {

            // Get the geofences that were triggered. A single event can trigger
            // multiple geofences.
            List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();

            // Get the transition details as a String.
            String geofenceTransitionDetails = getGeofenceTransitionDetails(
                    this,
                    geofenceTransition,
                    triggeringGeofences
            );

            // I havea problem creating a notification method in a non  Activity class
            sendNotification(geofenceTransitionDetails);
            Log.i(TAG, geofenceTransitionDetails);
        } else {
            // Log the error.
            Log.e(TAG,"An error occurred, try again in a little bit");
        }
    }
      //i have a major problem here getting the details and sending them
    private String getGeofenceTransitionDetails(GeofenceBroadcastReceiver geofenceBroadcastReceiver, int geofenceTransition, List<Geofence> triggeringGeofences) {

    }
}


I have a problem with the two areas highlighted in the second class, please help me make the getGeofenceTransitionDetailsand the ``sendNotification` methods work Thank You

  • 2
    When you have a Date object, turn it into a Calendar, and get the day of year from that. There is no point in turning your Date into a long. And hint: there are many new and better ways to go about dates and time than those two classes. – GhostCat Mar 11 '21 at 04:37
  • if you can explain that with an answer i can really appreciate it –  Mar 11 '21 at 04:45
  • 2
    I too recommend you don’t use `Calendar` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDate` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). Its `getDayOfYear()` method will give you what you want. – Ole V.V. Mar 11 '21 at 07:32
  • Are you using [Horiznotal-Calendar](https://github.com/Mulham-Raee/Horizontal-Calendar) for Android? – Ole V.V. Mar 11 '21 at 07:35
  • Why do expect me to explain something for you *again* that has been explained here, and in many other places many times before? The first "duplicate" question in that box that says "has answers here" ... tells you all you need to know. – GhostCat Mar 11 '21 at 08:48
  • @Olve V.V yeah am using a Horizontal Calendar and i just need to compute the Day of year from the ```long``` format time –  Mar 11 '21 at 09:09
  • `Instant.ofEpochMilli(selected).atZone(ZoneId.systemDefault()).getDayOfYear()` – Ole V.V. Mar 11 '21 at 20:05
  • Wow, great am gonna use that ,thanks for that really –  Mar 11 '21 at 20:12
  • i managed to disable days lesser than today on the horizontal calendar though but thanks –  Mar 11 '21 at 20:13

0 Answers0