How or why do listener interfaces work? And do interfaces have any other use rather than being a listener?

how to implement listener in java
types of listeners in java
java event listener example
inner class in event handling in java
java listener example
java events
types of events in java
java event listener framework

Whenever we want to create a listener, we implement a listener interface. For example, lets implement SensorEventListener.

Now we have to override the methods of this listener interface.

public void onSensorChanged(SensorEvent event);

and

public void onAccuracyChanged(Sensor sensor, int accuracy);

What I don't understand is:

  1. Why and how these methods work when I automatically use them?
  2. Why does onAccuracyChanged method gets called when the accuracy changes?
  3. After all, onAccuracyChanged is just an empty method that we override because our formula (or the interface we implement) requires us to do so. If it is something magical caused by the lower levels
  4. When and why would someone actually use an interface in his/her self-project regardless of android?

How or why do listener interfaces work? And do interfaces have any , And do interfaces have any other use rather than being a listener? how to implement listener in java types of listeners in java java custom event listener how do  Events require you to use listeners and to implement interfaces in order to receive notification of their occurrence. Although working with properties is simple, listener objects require a little extra discussion to understand how they work, typically in the graphical user interface (GUI) world.

Here is a suitable answer. Allow me to give you an example about listeners.

Listeners:

Suppose there is a class that fetches data in the background, the Worker, and another class that is interested in that data, the InterestedClass.

public class Worker extends Thread{
  interface DataFetchedListener{
    void onDataFetched(String data);
  }

  private DataFetchedListener listener;

  @Override
  public void run(){
   String data = fetchData();
   // Data fetched inform your listener so he can take action
   listener.onDataFetched(data);
  }

  public void setDataFetchedListener(DataFetchedListener listener){
   this.listener = listener;
  }

  private String fetchData(){
    // returns the fetched data after some operations
    return "Data";
  }
}


public class InterestedClass implements Worker.DatafetchedListener{

 @Override
 public void onDataFetched(String data){
  doSomethingWith(data);
 }

 private doSomethingWith(String data){
  // just print it in the console
  System.out.println("Data fetched is -> " + data);
 }

}

The Worker does not care which class will manipulate its data, as long as that class follows the contract of DataFetchedListener.

Equally this means that any class is able to do something with the data (InterestedClass just prints it in the console) but Worker does not need to know which class is that, just that it implements its interface.

The main could go like this...

public class Application{
  public static void main(String[] args){
   InterestedClass interested = new InterestedClass();
   Worker worker = new Worker();
   worker.setDataFetchedListener(intereseted);
   worker.start(); // Starts Worker's thread
  }
} 

When the Worker will fetch the data then it will notify its listener (currently the interested object) and the listener will act accordingly (interested will print the data to the console).

General Information about Writing Event Listeners (The Java , If you need to perform some lengthy operation as the result of an event, do it by This can be an easy architecture to maintain, but many classes can also mean reduced performance. whether you should use getSource or another method to get the event source. Some listener interfaces contain more than one method. The first alternative creates a named inner class (that implements the listener interface) while the second creates an anonymous class using that listener interface. Alternative 3) exposes the interface to the outer world, i.e. your class may be attached to some listener list (in some observable) it really wasn't meant for.

Interfaces have no implementation and for using them we have two options:

  1. A class that implement them
  2. An anonymous class

And consider this code:

interface TestInterface {
    void doSomething();
}

class TestClass{
    private TestInterface ti;
    public TestClass(TestInterface ti){
        this.ti = ti;
    }

    public void testActionMethod(){
        ti.doSomething();
        //some other codes
    }
}

class OurOwnLauncherApp{
    public static void main(String[] args) {
        TestClass tc = new TestClass(new TestInterface() {
            @Override
            public void doSomething() {
                System.out.println("Hi!");
            }
        });

        tc.testActionMethod();

        TestClass tc2 = new TestClass(new TestInterface() {
            @Override
            public void doSomething() {
                System.out.println("Bye!");
            }
        });

        tc2.testActionMethod();
    }
}

In here we have:

  1. An Interface (Just like what you asked)
  2. A function class the uses that interface
  3. An application somewhere that we don't know (Maybe your phone app, maybe your friends phone app, etc)

What this code does, it gives an anonymous class (which implements TestInterface) to the testActionMethod and with calling doSomething method inside testActionMethod, we invert the calling back to our own method. that's why you will see this result:

Hi!

Bye!

This is exactly a simplified version of listener interfaces and how they work

Introduction to Event Listeners (The Java™ Tutorials > Creating a , The Beeper class implements the ActionListener interface, which contains one A program can even have more than one listener for a single kind of event from a often components or models, but other kinds of objects can also be event sources. In How to Use Color Choosers, for instance, you will find an example of  Re: Public and Private listeners on the same interface DATA1 Thank you Bob and Valter, I was a bit confused because one document said that I should have 1 listener for incoming and 1 listener for outgoing emails, and another document stated that I can have 1 listener for both incoming and outgoing email.

There is no magic thing. Generally, the event-listener mechanism is as follow:

For some entities, there is the possibility to listen to some events on that entity (let name this entity as event generator). So some way should exist for other entities to listen to these changes (let name these entities as listeners). Now a listener registers itself as a listener of event generator. When an event occurs on the event generator, it calls the related method of registered listeners.

As a simple example assume a button. The button may generate an event for some actions such as click. Now if a listener wants to aware when the button is clicked, it should register itself as a listener of that button. On the other hand, the button should provide a unified way of registering the listeners. This unified way is the interface. Each entity which implements the interface could register itself as a listener for click on that button:

1- Listener implements the interface 2- Listener registers itself as a listener of button (Event Generator) 3- Event Generator calls the appropriate method of all registered listeners (this method is a method of the interface).

For your case, android provides a manager which you could register a listener on some sensors by it: android.hardware.SensorManager.registerListener(). All things occurs here (which is not magic!). When you register an entity (which implemented the related interface, SensorEventListener) as a sensor listener, changes in that sensor will cause to call methods of the listener).

Interfaces: Listeners and Adapters, The listener method itemStateChanged() doesn't do anything yet. Note, Unlike some other languages, Java does not have the ability to pass the memory The arrow points to the interface being implemented. We make draw an instance variable so we can use it throughout the class rather than just in the init() method. Your device may have several network interfaces. Those can correspond to real devices or be virtual. In order to be usable (i.e. initiate or listen for connections), each interface should have an IP address. Usually there will be one IP per interface, but it's possible to have several via IP aliasing.

Java SE 8 for Programmers, EventListener «interface» ActionListener «interface» ComponentListener «​interface» methods that must be declared in the class that implements the interface. the user interacted notifies its registered listeners by calling each listener's How does the GUI component know to call actionPerformed rather than some other  In Object oriented programming languages in short an interface is a Contract specification. Literally if you take it's English meaning, it is easier to understand.

Essential Visual J++ 6.0 fast: How to develop Java applications , In the next chapter we will be using the Abstract Windowing Toolkit (AWT) If you have used the previous model your applications will still work, but you The MouseListener interface has five methods, which each receive different Since Java does not support multiple inheritance you cannot extend more than one class,  Interfaces allow you to easily introduce new behaviour to your classes without altering their existing interfaces. Thus an interface allows for polymorphism independent of inheritance. This is very useful when you are trying to handle a number of completely different types of object in a similar manner. share.

Java¿ for Programmers: Java for Programmers _p2, When an event occurs, the GUI component with which the user interacted notifies its registered listeners by calling each listener's How does the GUI component know to call actionPerformed rather than another event-handling method? Let's illustrate how the event-handling mechanism works, using textField1 from the  The other example described in that section, MultiListener.java, has two action sources and two action listeners, with one listener listening to both sources and the other listening to just one. The Action Listener API. The ActionListener Interface. Because ActionListener has only one method, it has no corresponding adapter class.

Comments
  • I see, but one thing is not clear to me that, your interface was some sort of an "inner class" of Worker. But in Android, listeners are interfaces by themselves. So that part got me confused.
  • Oh... You can define the interface wherever you want. I just defined it inside Worker for consistency. As long as the interface is visible to the Worker and the the class which will implement it there is no problem!
  • But the part that I dont understand is, what is the relation of these "generators" with the "listeners". Is it defined in SensorManager that when accuracy changes, SensorManager expects an onAccuracyChanged method to exist in the caller class?