Custom event listener on Android app

89,168

Solution 1

  1. Define a callback interface

            public interface NewsUpdateListener 
            {
                void onNewsUpdate(<News data to be passed>);
            }
    
  2. Provide a registration facility on the background thread which gets the RSS feed

        class <Background processing class name> 
        {
        ....
            ArrayList<NewsUpdateListener> listeners = new ArrayList<NewsUpdateListener> ();
        .... 
            public void setOnNewsUpdateListener (NewsUpdateListener listener) 
            {
                // Store the listener object
                this.listeners.add(listener);
            }
        ....
        }
    
  3. Fire the callback when news is available

    ....
    for (listener : listeners) 
    {
        listener.onNewsUpdate(<News data to be passed>);
    }
    ....
    
  4. Register listener somewhere during initialization

    ....
        <class <Background processing class object>.registerListener
    (
        new OnNewsUpdateListener() {
            onNewsUpdate(<News Data>) {
                // process news data
                runOnUIThread(new Runnable() {
                    public void run() {
                        // refresh list view
                    }
                }
            }
    }
    ....
    

Solution 2

try this:

interface MyHandlerInterface
{
   void onHandle(Object obj)
}
class myListClass
{
   MyHandlerInterface myHandler;
   public void setHandlerListener(MyHandlerInterface listener)
   {
      myHandler=listener;
   }
   protected void myEventFired(myObj)
   {
      if(myHandler!=null)
         myHandler.onHandle(myObj);
   }
}

Solution 3

It sounds like you need a Handler - (look-up android.os.Handler for details).

The sendMessageDelayed method will allow you to schedule when the message is sent to your handler.

A quick search pulled up a full example that should get you started: http://www.tutorialforandroid.com/2009/01/using-handler-in-android.html

Solution 4

You can use android life cycle for that.

Create a signal interface, aka your event

interface NewsUpdateSignal{
    void newsUpdateHandler(Mydata data);
}

Than register to it inside your activity or anywhere else you want, there could be many listeners to same Signal.

class MyActivity extends Activity implements NewsUpdateSignal{
    Signal<NewsUpateSignal> newsUpdateSignal = SignalsBag.inject(NewsUpateSignal.class);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        newsUpdateSignal.addListener(this);        
    }

    @Override
    public void newsUpdateHandler(final Mydata data){
           //Do something here 
    }
}

And dispatch the signal when you need, from where ever you need.

Class A{
    Signal<NewsUpateSignal> newsUpdateSignal = SignalsBag.inject(NewsUpateSignal.class);

    void execute(){
        // obtain the data somehow, and dispatch it, the callback will be invoked on the same thread
        newsUpdateSignal.dispatcher.newsUpdateHandler(data);
    }        
}

Disclaimer: I am the author of android life cycle.

Share:
89,168
Bilthon
Author by

Bilthon

Updated on July 09, 2022

Comments

  • Bilthon
    Bilthon almost 2 years

    I need to set up a simple event listener to refresh a ListView once in a while. The problem is I don't know how could I generate an event.

    I know that for events like key or button pressing I just need to implement the Handler. But in this specific case I actually need to generate the event, which will be fired every time another running thread of my app wakes up and refreshes its list of news from an RSS feed.

    I've done everything, but got stuck in here. Can I get any suggestion or link with some more info on how to implement this?

  • radhoo
    radhoo almost 12 years
    This approach has the simplicity advantage, however Sameer's answer allows more then one listener to be set for one given event, a solution which I usually recommend.
  • radhoo
    radhoo almost 12 years
    This is not the best way to go, there are many situations when you need a prompt reaction on the listener side, and sendMessageDelayed/Handlers will add unwanted delays. Best approach is to create a listner interface and hold an array of listeners as per Sameer's example below.
  • 7heViking
    7heViking almost 9 years
    Can you elaborate on where to put the different snippets?
  • Mooing Duck
    Mooing Duck almost 9 years
    @FireFly3000: I think Snippet 2 is a java class that you want to have an event, snippet 1 can be in a seperate file, or be a subclass of 2. Snippet 3 should be a member of snippet 2. Snippet 4 goes in the class that wants to listen for the event.
  • Muhammad Riyaz
    Muhammad Riyaz almost 9 years
    Thanks for the Awesome solution. And what is the appropriate time to unregister a listener ? Since you are adding listeners into arrayList every time, When will you remove a listener ?
  • Daniel Cardenas
    Daniel Cardenas about 8 years
    This one is pretty interesting
  • Ilya Gazman
    Ilya Gazman about 8 years
    @DanielCardenas tnx, it's actually simpler now(You only need to create an interface for your event), I updated the answer to use the latest version of Life Cycle