0

I currently have a class that takes in the location of the object(so arguments keep changing), and I am initializing the class and running a function from the class every second in a thread, it returns an integer(-1 if doesn't exist or error). The integer that function returns is important because based on that integer, I will run a few other functions that will run on separate threads as well. Is there a way to convert all that process to using an Event Listener?

I basically want the event to trigger when the function in that class returns any number other than -1 and then I would run a separate thread with some functions from the MainActivity.

I looked at some other threads like Android Custom Event Listener, that was helpful to give me a good idea on how to do it, but I am not sure if it's possible to do it in my case and I tried doing what they said but it didn't work.

hm1233
  • 25
  • 7

1 Answers1

0

You can solve the above problem with your custom interface

  1. Create an interface

    interface LocationUpdateListener {
          int onLocationChanged(Location location);
    }
    
  2. In the class that is handling locations updates, add the list of update Listener

    List listeners = new ArrayList();

add an option to add listeners

 public void add(LocationUpdateListener listener) {
      listeners.add(listener); 
 }

and now use this list to update listeners

AndroidLocationUpdate.onLocationChanged(Location location) { //This is a method where new location comes.
    shoudlUpdateLocations(location);
}

private void shouldUpdateLocations(Location location) {
    if(location.getSpeed()>3) { //can have your own logic
        for(LocationUpdateListener listener : listeners) {
        listener.onLocationChanged(location);
        }
    }
}
  1. Add the listeners in your activity

class.add(this); //activity implement the interface

Hope it helps.

  • Thank you for your reply, is there a way I can trigger the listener on the function return rather than on the location update? For example, imagine I am calculating the speed of the of the object based on the location, I would return the speed value if it was between 5 and 30 mph/kph and I would return -1 otherwise. How can I trigger on the method's return value and not the location update? is it possible? If i trigger on the location update, it's going to trigger every few seconds as the location keeps changing – hm1233 Jun 28 '18 at 13:19
  • @Hussein I have updated my answer as per your query. This way you can control when to notify them. – Yogesh Madaan Jun 28 '18 at 23:37