17

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?

Community
  • 1
  • 1
OceanBlue
  • 9,142
  • 21
  • 62
  • 84

2 Answers2

52

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.

Brandon Romano
  • 1,022
  • 1
  • 13
  • 21
hackbod
  • 90,665
  • 16
  • 140
  • 154
  • 3
    Hi, I'm a little confused as to what you set the listener to in setTheListner() – Jon Wells Nov 24 '11 at 10:25
  • 1
    The class you want to be told about something happening implements the TheListener interface. You pass in the object implementing that interface to setTheListener(). – hackbod Nov 28 '11 at 03:27
  • 1
    @hackbod Should I call `new Something().setTheListener(this)` in the Class which implements **TheListener**? – Archie.bpgc Jul 04 '13 at 08:16
  • 1
    wow im confused...where does the definition for somethingHappened() go?? – mafiOSo Nov 15 '13 at 12:07
5

Just to clear things up;

you do exactly what @hackbod said and add this :

the activity which encloses the class (with the method setListener(Listener listen)), implements Listener and in it's oncreate or onResume or where-ever you call yourClass.setListener(this).

MHSaffari
  • 858
  • 1
  • 16
  • 39
MacD
  • 783
  • 7
  • 23