This article is reproduced on the blog of Dashen xiaanming( http://blog.csdn.net/xiaanming/article/details/17483273):
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 in class B in class A, and then invoke method D in class B in turn. This method is called callback method. In this way, do you feel a little dizzy? In fact, I just didn't understand it at first, and I read the classical theory. Callback mode:
- 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 asked him. Xiao Li didn't know at once. He told him that when I finished what I was doing, I would think about the answer. Xiao Wang would not be foolish to hold the phone and wait for Xiao Li's answer. So Xiao Wang said to Xiao Li, I still want to go shopping. If you know the answer, call me and tell him. I hung up and did my own business. An hour later, Xiao Li called Xiao Wang and told him the answer was 2.
Did you get a good idea of the callback mechanism through 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.
In the next article, I will summarize my understanding of callback mechanism in combination with this article.