Android EventBus 3.0.0 사용 요약(필수 편)

머리말
EventBus 프레임 워 크
EventBus 는 Google 에서 만 든 Guava,Guava 는 방대 한 라 이브 러 리 이 며 EventBus 는 그 에 따 른 작은 기능 일 뿐 실제 프로젝트 에 서 는 많이 사용 되 지 않 습 니 다.가장 많이 사용 하 는 것 은 green robot/EventBus 입 니 다.이 라 이브 러 리 의 장점 은 인터페이스 가 간결 하고 집적 이 편리 하지만 방법 명 을 제한 하여 주 해 를 지원 하지 않 습 니 다.또 다른 쿠 스 퀘 어/otto 는 Guava 에서 수정 하여 사용 하 는 사람 도 적지 않다.그래서 오늘 우리 가 연구 한 목 표 는 green robot 의 EventBus 입 니 다.
EventBus 안내
1.EventBus 3.0.0 은 최신 버 전 입 니 다.
2.EventBus 는 Android 게시/구독 이벤트 버스 로 Activities,Fragments,Threads,Services 등 구성 요소 간 의 메시지 전달 을 간소화 할 수 있 습 니 다.
3.Intent,Handler,BroadCast,인터페이스 등 전통 적 인 방안 을 대체 할 수 있 습 니 다.빠 르 고 코드 가 작 으 며 50K 정도 의 jar 가방 으로 코드 가 더욱 우아 하고 철저하게 결합 을 해제 합 니 다.
github 주소:https://github.com/greenrobot/EventBus
EventBus 원리 도

어떻게 의존 도 를 추가 합 니까?
module build.gredle 파일 의 dependencies 태그 에 추가
compile 'org.greenrobot:eventbus:3.0.0'
예컨대

apply plugin: 'com.android.application'

android {
  compileSdkVersion 24
  buildToolsVersion "24.0.3"

  defaultConfig {
    applicationId "com.eventbus.app"
    minSdkVersion 14
    targetSdkVersion 24
    versionCode 1
    versionName "1.0"

  }
  buildTypes {
    release {
      minifyEnabled false
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
  }
}

dependencies {
  compile fileTree(dir: 'libs', include: ['*.jar'])
  compile 'com.android.support:appcompat-v7:24.2.1'

  compile 'org.greenrobot:eventbus:3.0.0'
}
어떻게 사용 합 니까?
등록 이벤트
EventBus.getDefault().register( this );
등록 을 취소 하 다
EventBus.getDefault().unregister( this );
데이터 전송
EventBus.getDefault().post("내 가 쐈 어");
간단 한 예:EventBus 를 사용 하여 간단 한 문자열 전달

package com.eventbus.app;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class MainActivity extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //  
    EventBus.getDefault().register( this );


    findViewById( R.id.button).setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        EventBus.getDefault().post( "    ");
      }
    });
  }

  /**
   *         hello() ,      。
   *          
   * @return
   */

  @Subscribe(threadMode = ThreadMode.MAIN)
  public void hello ( String event){
    /* Do something */
    Toast.makeText( this , event , Toast.LENGTH_SHORT).show();
  };


  @Override
  protected void onDestroy() {
    super.onDestroy();

    //     ,   Activity    
    EventBus.getDefault().unregister( this );
  }
}
스 레 드 모델
이벤트 메 시 지 를 받 는 방법 에 서 는 주해 방식 으로 스 레 드 모델 을 설정 할 수 있 습 니 다.EventBus 에는 ThreadMode.POSTING,ThreadMode.MAIN,ThreadMode.BACK GROUND,ThreadMode.ASYNC 등 4 개의 스 레 드 모델 이 내장 되 어 있 습 니 다.
예 를 들 면:

@Subscribe(threadMode = ThreadMode.POSTING)
  public void onMessageEventPostThread(String event) {
    Log.e( "event PostThread", "  : " + event + " thread: " + Thread.currentThread().getName() );
  }

  @Subscribe(threadMode = ThreadMode.MAIN)
  public void onMessageEventMainThread(String event) {
    Log.e( "event MainThread", "  : " + event + " thread: " + Thread.currentThread().getName());
  }

  @Subscribe(threadMode = ThreadMode.BACKGROUND)
  public void onMessageEventBackgroundThread(String event) {
    Log.e( "event BackgroundThread", "  : " + event + " thread: " + Thread.currentThread().getName());
  }

  @Subscribe(threadMode = ThreadMode.ASYNC)
  public void onMessageEventAsync(String event) {
    Log.e( "event Async", "  : " + event + " thread: " + Thread.currentThread().getName());
  }
PostThread:이벤트 처리 함 수 를 사용 하여 스 레 드 모델 을 PostThread 로 지정 하면 이 사건 이 어느 스 레 드 에서 발표 되 었 는 지 이벤트 처리 함 수 는 이 스 레 드 에서 실 행 됩 니 다.즉,발표 이벤트 와 수신 이벤트 가 같은 스 레 드 에 있 습 니 다.스 레 드 모델 이 PostThread 인 이벤트 처리 함수 에서 시간 소모 작업 을 피 하 는 것 은 이벤트 의 전달 을 막 고 ANR 을 일 으 킬 수 있 기 때 문 입 니 다.
MainThread:이벤트 처리 함 수 를 사용 하여 스 레 드 모델 을 MainThread 로 지정 하면 이벤트 가 어느 스 레 드 에서 발표 되 든 이 이벤트 처리 함 수 는 UI 스 레 드 에서 실 행 됩 니 다.이 방법 은 UI 를 업데이트 하 는 데 사용 할 수 있 지만 시간 소모 작업 은 처리 할 수 없습니다.
BackgroundThread:이벤트 처리 함 수 를 사용 하여 스 레 드 모델 을 BackgroundThread 로 지정 하면 이벤트 가 UI 스 레 드 에서 발 표 된 경우 이 이벤트 처리 함 수 는 새로운 스 레 드 에서 실 행 됩 니 다.이벤트 가 원래 하위 스 레 드 에서 발 표 된 경우 이 이벤트 처리 함 수 는 발표 이벤트 의 스 레 드 에서 실 행 됩 니 다.이 이벤트 처리 함수 에 서 는 UI 업데이트 작업 이 금지 되 어 있 습 니 다.
Async:이벤트 처리 함 수 를 사용 하여 스 레 드 모델 을 Async 로 지정 하면 이벤트 가 어느 스 레 드 에서 발표 되 든 이 이벤트 처리 함 수 는 새 하위 스 레 드 에서 실 행 됩 니 다.마찬가지 로 이 이벤트 처리 함수 에 서 는 UI 업데이트 작업 이 금지 되 어 있 습 니 다.
작은 예 1:하위 스 레 드 에서 데 이 터 를 보 냅 니 다.

package com.eventbus.app;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class MainActivity extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //  
    EventBus.getDefault().register( this );

    findViewById( R.id.button).setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        new Thread(new Runnable() {
          @Override
          public void run() {
            Log.d( "event        : " , Thread.currentThread().getName() ) ;
            EventBus.getDefault().post( "    ");
          }
        }).start() ;
      }
    });
  }


  @Subscribe(threadMode = ThreadMode.POSTING)
  public void onMessageEventPostThread(String event) {
    Log.e( "event PostThread", "  : " + event + " thread: " + Thread.currentThread().getName() );
  }

  @Subscribe(threadMode = ThreadMode.MAIN)
  public void onMessageEventMainThread(String event) {
    Log.e( "event MainThread", "  : " + event + " thread: " + Thread.currentThread().getName());
  }

  @Subscribe(threadMode = ThreadMode.BACKGROUND)
  public void onMessageEventBackgroundThread(String event) {
    Log.e( "event BackgroundThread", "  : " + event + " thread: " + Thread.currentThread().getName());
  }

  @Subscribe(threadMode = ThreadMode.ASYNC)
  public void onMessageEventAsync(String event) {
    Log.e( "event Async", "  : " + event + " thread: " + Thread.currentThread().getName());
  }


  @Override
  protected void onDestroy() {
    super.onDestroy();

    //     ,   Activity    
    EventBus.getDefault().unregister( this );
  }
}
실행 결과:
D/event 발사 데이터 스 레 드::Thread-109
E/event Background Thread:메시지:thread 를 발 사 했 습 니 다:Thread-109
E/event PostThread:메시지:thread 를 발 사 했 습 니 다:Thread-109
E/event Async:소식:thread 를 발 사 했 습 니 다:pool-1-thread-2
E/event MainThread:메시지:thread:main 을 발 사 했 습 니 다.
작은 예 2:메 인 스 레 드 에서 데 이 터 를 보 냅 니 다.

package com.eventbus.app;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class MainActivity extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //  
    EventBus.getDefault().register( this );

    findViewById( R.id.button).setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Log.d( "event        : " , Thread.currentThread().getName() ) ;
        EventBus.getDefault().post( "    ");
      }
    });
  }

  @Subscribe(threadMode = ThreadMode.POSTING)
  public void onMessageEventPostThread(String event) {
    Log.e( "event PostThread", "  : " + event + " thread: " + Thread.currentThread().getName() );
  }

  @Subscribe(threadMode = ThreadMode.MAIN)
  public void onMessageEventMainThread(String event) {
    Log.e( "event MainThread", "  : " + event + " thread: " + Thread.currentThread().getName());
  }

  @Subscribe(threadMode = ThreadMode.BACKGROUND)
  public void onMessageEventBackgroundThread(String event) {
    Log.e( "event BackgroundThread", "  : " + event + " thread: " + Thread.currentThread().getName());
  }

  @Subscribe(threadMode = ThreadMode.ASYNC)
  public void onMessageEventAsync(String event) {
    Log.e( "event Async", "  : " + event + " thread: " + Thread.currentThread().getName());
  }


  @Override
  protected void onDestroy() {
    super.onDestroy();

    //     ,   Activity    
    EventBus.getDefault().unregister( this );
  }
}
실행 결과:
D/event 발사 데이터 스 레 드::main
E/event MainThread:메시지:thread:main 을 발 사 했 습 니 다.
E/event PostThread:메시지:thread:main 을 발 사 했 습 니 다.
E/event Async:소식:thread 를 발 사 했 습 니 다:pool-1-thread-3
E/event BackgroundThread:메시지:thread 를 발 사 했 습 니 다:pool-1-thread-4
점성 사건
위 에서 말 한 일반 이벤트 외 에 EventBus 는 점성 이벤트 발송 도 지원 합 니 다.점성 사건 은 무엇 입 니까?쉽게 말 하면 사건 을 보 낸 뒤 이 사건 을 구독 해도 이 사건 을 받 을 수 있 고 점성 방송 과 유사 하 다.구체 적 인 용법 은 다음 과 같다.
책.
EventBus.getDefault().register( this );
이벤트 수신

@Subscribe(threadMode = ThreadMode.MAIN , sticky = true )
public void onMessageEventMainThread(String event) {
Log.e( "event MainThread", "  : " + event + " thread: " + > Thread.currentThread().getName());
}
등록 을 취소 하 다
EventBus.getDefault().unregister( this ) ;
송신 이벤트
EventBus.getDefault().postSticky("내 가 쐈 어");
작은 예:MainActivity 에서 이 벤트 를 보 내 고 Activity 2 에 이 벤트 를 등록 하고 받 습 니 다.
MainActivity 원본 코드

package com.eventbus.app;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import org.greenrobot.eventbus.EventBus;

public class MainActivity extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    findViewById( R.id.button).setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Log.d( "event        : " , Thread.currentThread().getName() ) ;
        EventBus.getDefault().postSticky( "    ");

        startActivity( new Intent( MainActivity.this , Activity2.class ));
      }
    });
  }
}
Activity 2 소스 코드

package com.eventbus.app;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class Activity2 extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_2);
    //  
    EventBus.getDefault().register( this );
  }

  @Subscribe(threadMode = ThreadMode.MAIN , sticky = true )
  public void onMessageEventMainThread(String event) {
    Log.e( "event MainThread", "  : " + event + " thread: " + Thread.currentThread().getName());
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    //     ,   Activity    
    EventBus.getDefault().unregister( this ) ;
  }
}
이것 이 바로 점성 이벤트 로 구독 전에 보 낸 메 시 지 를 받 을 수 있 습 니 다.그러나 이 는 최신 소식 만 받 을 수 있다.예 를 들 어 구독 하지 않 기 전에 여러 개의 점성 메 시 지 를 보 낸 다음 에 구독 하면 가장 가 까 운 소식 만 받 을 수 있다.
EventBus 소스 코드 분석
구독 인터페이스 원본 코드

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Subscribe {
  ThreadMode threadMode() default ThreadMode.POSTING;

  /**
   * If true, delivers the most recent sticky event (posted with
   * {@link EventBus#postSticky(Object)}) to this subscriber (if event available).
   */
  boolean sticky() default false;

  /** Subscriber priority to influence the order of event delivery.
   * Within the same delivery thread ({@link ThreadMode}), higher priority subscribers will receive events before
   * others with a lower priority. The default priority is 0. Note: the priority does *NOT* affect the order of
   * delivery among subscribers with different {@link ThreadMode}s! */
  int priority() default 0;
}
기본 스 레 드 모델 은 ThreadMode.POSTING 임 을 알 수 있 습 니 다.기본 점성 이 벤트 는 false 입 니 다.즉,점성 이 벤트 를 열지 않 는 것 을 기본 으로 합 니 다.기본 선택 단 계 는 0 입 니 다.
EventBus 클래스 부분 소스 코드

static volatile EventBus defaultInstance;
 
  /** Convenience singleton for apps using a process-wide EventBus instance. */
  public static EventBus getDefault() {
    if (defaultInstance == null) {
      synchronized (EventBus.class) {
        if (defaultInstance == null) {
          defaultInstance = new EventBus();
        }
      }
    }
    return defaultInstance;
  }
getDefault()는 하나의 예 모드 로 하나의 인 스 턴 스 대상 만 있 습 니 다.
ThreadMode 클래스 소스 코드

public enum ThreadMode {

  /**
   * Subscriber will be called in the same thread, which is posting the event. This is the default. Event delivery
   * implies the least overhead because it avoids thread switching completely. Thus this is the recommended mode for
   * simple tasks that are known to complete is a very short time without requiring the main thread. Event handlers
   * using this mode must return quickly to avoid blocking the posting thread, which may be the main thread.
   */
   
  POSTING,

  /**
   * Subscriber will be called in Android's main thread (sometimes referred to as UI thread). If the posting thread is
   * the main thread, event handler methods will be called directly. Event handlers using this mode must return
   * quickly to avoid blocking the main thread.
   */
   
  MAIN,

  /**
   * Subscriber will be called in a background thread. If posting thread is not the main thread, event handler methods
   * will be called directly in the posting thread. If the posting thread is the main thread, EventBus uses a single
   * background thread, that will deliver all its events sequentially. Event handlers using this mode should try to
   * return quickly to avoid blocking the background thread.
   */
   
  BACKGROUND,

  /**
   * Event handler methods are called in a separate thread. This is always independent from the posting thread and the
   * main thread. Posting events never wait for event handler methods using this mode. Event handler methods should
   * use this mode if their execution might take some time, e.g. for network access. Avoid triggering a large number
   * of long running asynchronous handler methods at the same time to limit the number of concurrent threads. EventBus
   * uses a thread pool to efficiently reuse threads from completed asynchronous event handler notifications.
   */

  ASYNC
}
이 클래스 는 매 거 진 클래스 로 스 레 드 모델 의 몇 가지 유형 을 정의 합 니 다.
이상 의 안 드 로 이 드 이 벤트 버스 3.0.0 사용 총화(필수 편)는 바로 편집장 이 여러분 에 게 공유 한 모든 내용 입 니 다.여러분 에 게 참고 가 될 수 있 고 많은 사랑 을 바 랍 니 다.

좋은 웹페이지 즐겨찾기