Programming

안드로이드에서 콜백을 정의하는 방법?

procodes 2020. 6. 12. 23:20
반응형

안드로이드에서 콜백을 정의하는 방법?


가장 최근의 Google IO 동안 편안한 클라이언트 응용 프로그램 구현에 대한 프레젠테이션이있었습니다. 불행히도, 구현의 소스 코드가없는 높은 수준의 토론이었습니다.

이 다이어그램에서 리턴 경로에는 다른 메소드에 대한 다양한 콜백이 있습니다.

Google iOS 프레젠테이션 슬라이드

이 방법들이 무엇인지 어떻게 선언합니까?

콜백이라는 아이디어를 이해합니다. 특정 이벤트가 발생한 후 호출되는 코드이지만 구현 방법을 모르겠습니다. 지금까지 콜백을 구현 한 유일한 방법은 다양한 메소드 (예 : onActivityResult)를 재정의했습니다.

디자인 패턴에 대한 기본 지식이 있다고 생각하지만 리턴 경로를 처리하는 방법에 대해 계속해서 넘어갑니다.


대부분의 경우 인터페이스가 있으며이를 구현하는 객체를 전달합니다. 예를 들어 대화 상자에는 OnClickListener가 있습니다.

임의의 예와 마찬가지로 :

// The callback interface
interface MyCallback {
    void callbackCall();
}

// The class that takes the callback
class Worker {
   MyCallback callback;

   void onEvent() {
      callback.callbackCall();
   }
}

// Option 1:

class Callback implements MyCallback {
   void callbackCall() {
      // callback code goes here
   }
}

worker.callback = new Callback();

// Option 2:

worker.callback = new MyCallback() {

   void callbackCall() {
      // callback code goes here
   }
};

아마도 옵션 2의 구문을 엉망으로 만들었습니다.


내 견해에서 무언가가 발생하면 내 활동이 듣고있는 이벤트를 시작합니다.

// (사용자 정의)보기에서 선언

    private OnScoreSavedListener onScoreSavedListener;
    public interface OnScoreSavedListener {
        public void onScoreSaved();
    }
    // ALLOWS YOU TO SET LISTENER && INVOKE THE OVERIDING METHOD 
    // FROM WITHIN ACTIVITY
    public void setOnScoreSavedListener(OnScoreSavedListener listener) {
        onScoreSavedListener = listener;
    }

// 활동 선언

    MyCustomView slider = (MyCustomView) view.findViewById(R.id.slider)
    slider.setOnScoreSavedListener(new OnScoreSavedListener() {
        @Override
        public void onScoreSaved() {
            Log.v("","EVENT FIRED");
        }
    });

조각 간의 통신 (콜백)에 대한 자세한 내용은 다음을 참조하십시오. http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity


기존 인터페이스를 사용할 수있을 때 새 인터페이스를 정의 할 필요가 없습니다 android.os.Handler.Callback. 콜백 유형의 객체를 전달하고 콜백을 호출 handleMessage(Message msg)합니다.


인터페이스를 사용하여 콜백 메소드를 구현하는 예제입니다.

NewInterface.java 인터페이스를 정의하십시오 .

패키지 javaapplication1;

public interface NewInterface {
    void callback();
}

Create a new class, NewClass.java. It will call the callback method in main class.

package javaapplication1;

public class NewClass {

    private NewInterface mainClass;

    public NewClass(NewInterface mClass){
        mainClass = mClass;
    }

    public void calledFromMain(){
        //Do somthing...

        //call back main
        mainClass.callback();
    }
}

The main class, JavaApplication1.java, to implement the interface NewInterface - callback() method. It will create and call NewClass object. Then, the NewClass object will callback it's callback() method in turn.

package javaapplication1;
public class JavaApplication1 implements NewInterface{

    NewClass newClass;

    public static void main(String[] args) {

        System.out.println("test...");

        JavaApplication1 myApplication = new JavaApplication1();
        myApplication.doSomething();

    }

    private void doSomething(){
        newClass = new NewClass(this);
        newClass.calledFromMain();
    }

    @Override
    public void callback() {
        System.out.println("callback");
    }

}

to clarify a bit on dragon's answer (since it took me a while to figure out what to do with Handler.Callback):

Handler can be used to execute callbacks in the current or another thread, by passing it Messages. the Message holds data to be used from the callback. a Handler.Callback can be passed to the constructor of Handler in order to avoid extending Handler directly. thus, to execute some code via callback from the current thread:

Message message = new Message();
<set data to be passed to callback - eg message.obj, message.arg1 etc - here>

Callback callback = new Callback() {
    public boolean handleMessage(Message msg) {
        <code to be executed during callback>
    }
};

Handler handler = new Handler(callback);
handler.sendMessage(message);

편집 : 방금 동일한 결과를 얻는 더 좋은 방법이 있다는 것을 깨달았습니다 (콜백을 정확히 언제 실행할지 제어).

post(new Runnable() {
    @Override
    public void run() {
        <code to be executed during callback>
    }
});

LocalBroadcast이 목적으로 도 사용할 수 있습니다 . 여기 빠른 퀘스트가 있습니다

방송 수신기를 만듭니다.

   LocalBroadcastManager.getInstance(this).registerReceiver(
            mMessageReceiver, new IntentFilter("speedExceeded"));

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Double currentSpeed = intent.getDoubleExtra("currentSpeed", 20);
        Double currentLatitude = intent.getDoubleExtra("latitude", 0);
        Double currentLongitude = intent.getDoubleExtra("longitude", 0);
        //  ... react to local broadcast message
    }

이것이 당신이 그것을 트리거 할 수있는 방법입니다

Intent intent = new Intent("speedExceeded");
intent.putExtra("currentSpeed", currentSpeed);
intent.putExtra("latitude", latitude);
intent.putExtra("longitude", longitude);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

onPause에서 수신자 등록 취소 :

protected void onPause() {
  super.onPause();
  LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
}

참고 URL : https://stackoverflow.com/questions/3398363/how-to-define-callbacks-in-android

반응형