Custom event listener on Android app

Bilthon picture Bilthon · Jun 6, 2010 · Viewed 88.3k times · Source

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?

Answer

Sameer picture Sameer · Feb 5, 2012
  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
                    }
                }
            }
    }
    ....