[Android, EventBus] 이벤트 버스 사용법
Sqare 에서 만든 Otto 라이브러리 event bus 사용법에 대해 알아보겠습니다.
otto git hub 주소 : https://github.com/square/otto
아래 예제는
Fragment1 과 Fragment2 가 메시지를 주고받는 예제입니다.
1. Gradle 추가
compile 'com.squareup:otto:1.3.7'
2. 전역에서 같은 객체를 가지고 오기위한 싱글톤인 Global Bus 생성
public class GlobalBus {
private static Bus sBus;
public static Bus getBus() {
if (sBus == null)
sBus = new Bus();
return sBus;
}
}
3. 이벤트 버스에서 실행 시킬 메서드가 있는 Events 생성
public class Events {
public static class Event1 {
private String message;
public Event1(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
}
3. 이벤트 버스의 결과를 받을 곳에 Subscribe 설정 (Fragment1)
- Fragment1 에 GlobalBus 을 등록해 줍니다.
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GlobalBus.getBus().register(this);
}
- 물론 Fragment1 이 삭제 되면 등록을 해지 또한 해주어야 합니다.
@Override
public void onDestroyView() {
super.onDestroyView();
GlobalBus.getBus().unregister(this);
}
- @Subscribe 어노테이션 아래에 connectEvent1 이름의 함수를 구독합니다. (connectEvent1 의 이름은 아무거나 적으셔도 됩니다.)
- connectEvent1 변수 안에 Events 클래스에서 Event1 을 넣어줍니다.
- Fragment2 에서 이벤트 버스를 post 하였을 때 보낸 메시지를 로그에 찍을 수 있습니다.
@Subscribe
public void connectEvent1(Events.Event1 event1) {
Log.i("MyTag", event1.getMessage());
}
4. 이벤트 버스를 보낼 곳에 post 를 호출하여 구독 되어진 곳으로 정보를 전달 (Fragment2)
Events.Event1 event1 =
new Events.Event1("Fragment1 으로 메시지 전달");
GlobalBus.getBus().post(event1);
이렇게 서로 다른 화면에서 메시지를 주고받을 수 있는 예제를 해보았습니다.
참고 사이트
http://gun0912.tistory.com/4