什么是回调的Andr​​oid?回调、Andr、oid

2023-09-12 10:49:08 作者:法海乜纞じòぴé

我想了解回调的概念。我搜索在互联网上有关的回调,有使用的接口很多例子,一类是通过调用该接口另一个类的方法。但我仍不能得到回调的主要概念,什么是使用回调的目的是什么?

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类取得一个线程做了一些工作。如果线程完成了工作,它会通知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.之间的活动和片段。由于碎片应该是模块化的,你可以在片段来调用活动的方法定义一个回调。

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.