1、写一个接口:
public interface CountInterface {
public void CountValue(String value);
}
2、写一个Test类:
public class Test {
int countsum;
private CountInterface countcallback;
public void setCallBack(int x, int y, CountInterface countcallback) {
this.countcallback = countcallback;
countsum = x + y;
}
public void count() {
countcallback.CountValue(countsum + "");
}
}
3、MainActivity类onCreate()函数下:
Test test = new Test();
test.setCallBack(2, 5, new CountInterface() {
//回调函数
@Override
public void CountValue(String value) {
System.out.println("回调函数中的值:" + value );
}
});
//执行下面的代码才会执行回调函数中的代码
test.count();
理解:
1、回调函数就是一个通过函数指针来调用的函数。因为java没办法操作指针,于是它用接口来实现。
如果将函数A的指针(地址,引用)(CountValue函数)通过形参传递到另一个类(Test类)的某个函数里,那么当这个类(Test类)调用该函数里面我所传入的指针时,就能调用函数A。
2、实现了一个接口里的方法CountValue,然后注册到Test类,然后可以去做别的事情去了,Test类在某个触发的时机(test.count();)回头来调用CountValue的方法。
3、回调过程就是传入函数A的地址,Test类接收,并在某个时刻回调这边的A函数。
4、有些库函数(library function)要求应用先传给它一个函数,好在合适的时候调用,以完成目标任务。这个被传入的、后又被调用的函数就称为回调函数(callback function)。
5、以通知替代轮询,回调函数CountValue()不用一直询问是否需要执行,它只需等待一个通知(回调)执行。