java callback mechanism Classical examples
In the past, I did not understand what callback was. Every day I heard people say to add a callback method. I thought to myself, what is called callback method? Then I look for it on the internet, and I don't know much about it. Now I know that the so-called callback is to call a method C of class B in class A, and then invoke method D of class A in class B. This method is called callback method. In this way, do you feel a little dizzy? In fact, I just started. It is so incomprehensible that we have seen the classical way of callback.
- Class A Implementation Interface CallBack callback - Background 1
- ClassA contains a reference b to class B -- Background 2
- ClassB has a method f(CallBack callback) with a parameter called back -- background 3
- Object a of A calls method f(CallBack callback) of B -- Class A calls method C of Class B
- Then B can call the method of A in f(CallBack callback) - Class B calls a method D of Class A.
Everyone likes to use the example of telephone, well, in order to keep up with the times, I also use this example, I use the example of asynchronous plus callback.
One day Xiao Wang met a very difficult question. The question was "1 + 1 =?". He called Xiao Li and said to him that when I finished what I was doing, I would think about the answer. Xiao Wang would not be foolish to wait for Xiao Li's answer with the phone. So Xiao Wang said to Xiao Li, I still need to go. Go shopping, you know the answer, call me and tell me, so hang up, do their own business, an hour later, Xiao Li called Xiao Wang, telling him the answer is 2
Do you understand the callback mechanism almost by the example above? It's an asynchronous callback. Let's look at the synchronous callback, onClick () method.
Now let's analyse it. Android View's click method onclick(); we know that onclick() is a callback method. When a user clicks View, this method is executed. Let's use Button as an example.
The following is the setOnClickListener method of the View class, which is equivalent to Class B and only pastes out the key code.
This example is a typical Android callback mechanism. After reading this, do you have a better understanding of the callback mechanism? Thread run() is also a callback method. When the start () method of Thread is executed, it calls back the run() method, and the processing of messages is classical, and so on.