android開發筆記之EventBus

EventBus 簡介

github EventBus
https://github.com/greenrobot/EventBus

其描述爲:
Event bus for Android and Java that simplifies communication between Activities, Fragments, Threads, Services, etc. Less code, better quality

其實現原理爲:
在這裏插入圖片描述
其特點爲:

  • simplifies the communication between components

decouples event senders and receivers
performs well with Activities, Fragments, and background threads
avoids complex and error-prone dependencies and life cycle issues
makes your code simpler

  • is fast
  • is tiny (~50k jar)
  • is proven in practice by apps with 100,000,000+ installs
  • has advanced features like delivery threads, subscriber priorities,
    etc.

EventBus使用具體方法爲:
(1)在build.gradle添加庫依賴

dependencies {
    implementation 'org.greenrobot:eventbus:3.1.1'
}

(2)Define events:

public static class MessageEvent { /* Additional fields if needed */ }

(3)Prepare subscribers: Declare and annotate your subscribing method, optionally specify a thread mode:

@Subscribe(threadMode = ThreadMode.MAIN)  
public void onMessageEvent(MessageEvent event) {/* Do something */};

Register and unregister your subscriber. For example on Android, activities and fragments should usually register according to their life cycle:

 @Override
 public void onStart() {
     super.onStart();
     EventBus.getDefault().register(this);
 }

 @Override
 public void onStop() {
     super.onStop();
     EventBus.getDefault().unregister(this);
 }

(4)Post events:

EventBus.getDefault().post(new MessageEvent());

EventBus3.0有四種線程模型,分別是:

  • POSTING:默認,表示事件處理函數的線程跟發佈事件的線程在同一個線程。
  • MAIN:表示事件處理函數的線程在主線程(UI)線程,因此在這裏不能進行耗時操作。
  • BACKGROUND:表示事件處理函數的線程在後臺線程,因此不能進行UI操作。如果發佈事件的線程是主線程(UI線程),那麼事件處理函數將會開啓一個後臺線程,如果果發佈事件的線程是在後臺線程,那麼事件處理函數就使用該線程。
  • ASYNC:表示無論事件發佈的線程是哪一個,事件處理函數始終會新建一個子線程運行,同樣不能進行UI操作。

粘性事件:
所謂粘性事件,就是在發送事件之後再訂閱該事件也能收到該事件。請注意這裏與普通事件的區別,普通事件是先註冊在綁定。
比如在項目中有這樣的需求,在FirstActivity發送事件,到SecondActivity中做事件的處理。如果是使通過EventBus.getDefault.post(xx)發出的,在SecondActivity是接收不到消息的。 主要原因是SecondActivit用於接收消息的EventBus還未完成註冊,也就是發佈者發了消息,但訂閱者還未產生。

發送粘性事件:

EventBus.getDefault().postSticky(messageEvent);

處理粘性事件:

@Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
public void XXX(MessageEvent messageEvent) {
    ...
}

EventBus Demo

主要實現功能是,從第二個界面發送一個消息回第一個界面,並在第一個界面的TextView中來顯示此消息.

效果如圖:
在這裏插入圖片描述

實現邏輯:
(1)在build.gradle添加庫依賴

dependencies {
    implementation 'org.greenrobot:eventbus:3.1.1'
}

(2)定義傳遞消息

public class MessageEvent {

    private String message;

    public  MessageEvent(String message){
        this.message=message;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

(3)第一個界面實現邏輯:

public class EventBusDemoMainActivity extends AppCompatActivity {

    private TextView textView;
    private Button button;

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

    private void init() {
        EventBus.getDefault().register(this);

        textView = (TextView) findViewById(R.id.textView);
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onDoClick();
            }
        });
    }

    private void onDoClick() {
        Intent intent=new Intent(EventBusDemoMainActivity.this,SecondActivity.class);
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(MessageEvent messageEvent) {
        textView.setText(messageEvent.getMessage());
    }

}

第二個界面實現邏輯:

public class SecondActivity extends AppCompatActivity {

    private Button button;

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

    private void init() {
        button = (Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EventBus.getDefault().post(new MessageEvent("我是使用EventBus發送的第一個消息噢,親!"));
                finish();
            }
        });
    }
}

參考資料

1.EventBus 3.0使用詳解
https://www.jianshu.com/p/f9ae5691e1bb
2.Android EventBus 的使用
https://www.jianshu.com/p/e7d5c7bda783

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章