Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

Custom event listener on Android app

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?

question from:https://stackoverflow.com/questions/2983250/custom-event-listener-on-android-app

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  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
                    }
                }
            }
    }
    ....
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...