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
175 views
in Technique[技术] by (71.8m points)

android - How to implement a listener

I have a design issue. I need to implement a listener. I saw the following SO question: How to create our own Listener interface in android?

But in the link it provides in the answer, author creates a listener which just extends the system-defined listener. E.g onClick, you would do some validation & then call another method called "whenValidatedListener"

I need to define listeners which are not linked to existing event listeners. Basically there would be some processing going on in native(C/C++) code & in the Android code I need a listener to respond to certain messages from it.

I think I could do this using handlers. But AsyncTask is the recommended approach for multithreading.

Is there a way to implement a user-defined-listener using AsyncTask?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

AsyncTask has nothing to do with implementing a listener.

Here's a listener:

public interface TheListener {
    public void somethingHappened();
}

Call it however you want. For example, here's a class doing something like View:

public class Something {
    private TheListener mTheListener;

    public void setTheListener(TheListener listen) {
        mTheListener = listen;
    }

    private void reportSomethingChanged() {
        if (mTheListener != null) {
            mTheListener.somethingHappened();
        }
    }
}

You can make this as complicated as you want. For example, instead of a single listener pointer you could have an ArrayList to allow multiple listeners to be registered.

Calling this from native code also has nothing to do with implementing a listener interface. You just need to learn about JNI to learn how native code can interact with Java language code.


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

...