如何实现一个监听器监听器、如何实现

2023-09-12 10:59:56 作者:请滚的麻利些,谢了!

我有一个设计问题。我需要实现一个监听器。我看到下面的SO问题: How在Android的创建自己的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?

但它提供了答案的链接,笔者创建了刚刚扩展了系统定义的监听器的监听器。例如的onClick,你会做一些验证和放大器;然后调用另一个名为whenValidatedListener法

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"

我需要确定哪些未链接到现有的事件侦听器监听。基本上会有一些加工机(C / C ++)code和事;在Android code,我需要一个侦听器,它响应某些消息。

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.

我想我可以使用处理程序做到这一点。但AsyncTask的是多线程的推荐方法。

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

有没有办法实现使用AsyncTask的用户自定义的监听?

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

推荐答案

的AsyncTask无关与执行的监听器。

AsyncTask has nothing to do with implementing 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();
        }
    }
}

您可以只要你想这是复杂的。而不是一个单一的监听器。例如,指针你可以有一个ArrayList,允许多个监听器进行注册。

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.

从本地code调用这也有无关,与实施监听器接口。你只需要了解JNI来学习如何本地code可以用Java语言code交互。

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.