Android中的回调是什么? [英] What is callback in Android?
问题描述
我想了解回调的概念.我在互联网上搜索了有关回调的信息,并且有很多使用接口的示例,一个类正在使用该接口调用另一个类的方法.但是还是没搞懂回调的主要概念,使用回调的目的是什么?
I want to understand the concept of callback. I have searched on internet about the callbacks and there are many examples using interface, and one class is calling a method of another class using that interface. But still I can't get the main concept of callbacks, what is the purpose of using callbacks?
推荐答案
这里有一个很好的 教程,很好地描述了回调和用例.
Here is a nice tutorial, which describes callbacks and the use-case well.
回调的概念是通知一个类同步/异步另一个类中的某些工作是否完成.有人称之为好莱坞原则:不要叫我们我们叫你".
The concept of callbacks is to inform a class synchronous / asynchronous if some work in another class is done. Some call it the Hollywood principle: "Don't call us we call you".
举个例子:
class A implements ICallback {
MyObject o;
B b = new B(this, someParameter);
@Override
public void callback(MyObject o){
this.o = o;
}
}
class B {
ICallback ic;
B(ICallback ic, someParameter){
this.ic = ic;
}
new Thread(new Runnable(){
public void run(){
// some calculation
ic.callback(myObject)
}
}).start();
}
interface ICallback{
public void callback(MyObject o);
}
A 类调用 B 类以在线程中完成一些工作.如果 Thread 完成工作,它将通过回调通知 Class A 并提供结果.所以不需要轮询什么的.您将在结果可用后立即获得结果.
Class A calls Class B to get some work done in a Thread. If the Thread finished the work, it will inform Class A over the callback and provide the results. So there is no need for polling or something. You will get the results as soon as they are available.
在 Android 中使用回调函数 f.e.活动和片段之间.因为 Fragment 应该是模块化的,所以你可以在 Fragment 中定义一个回调来调用 Activity 中的方法.
In Android Callbacks are used f.e. between Activities and Fragments. Because Fragments should be modular you can define a callback in the Fragment to call methods in the Activity.
这篇关于Android中的回调是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!