天天看點

【開源架構】EventBus 消息總線使用開源架構 —> EventBus 消息總線架構使用1. 前言2. 實戰

開源架構 —> EventBus 消息總線架構使用

标簽(空格分隔): EventBus Android架構

  • 開源架構 EventBus 消息總線架構使用
  • 前言
  • 實戰
    • 1 基本使用方法
      • 1 自定義一個消息類
      • 2 接受消息的界面注冊與反注冊以及接收消息後實作
      • 3 發送消息

1. 前言

OTA子產品用到消息總線架構EventBus,經過對比handler,項目中消息比較多,使用EventBus架構,便于統一管理

EventBus是一款針對Android優化的釋出/訂閱事件總線。主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,線程之間傳遞消息.優點是開銷小,代碼更優雅。以及将發送者和接收者解耦

下載下傳EventBus架構類庫

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

2. 實戰

2.1 基本使用方法

(1) 自定義一個消息類

public class MyEventBus{
   public static final int JUMP_TO_NETWORKSETTINGS = ;
    public static final int RETURN_TO_SECONDPAGER = ;
    private String message;
    private int what;

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

    public MessageEvent(int what) {
        this.what = what;
    }

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

    public String getMessage() {
        return message;
    }

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

    public int getWhat() {
        return what;
    }

    public void setWhat(int what) {
        this.what = what;
    }
}
           

(2) 接受消息的界面注冊與反注冊,以及接收消息後實作

//OnCreate函數中注冊EventBus
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //注冊EventBus
    EventBus.getDefault().register(this);
}

//OnDestory函數中反注冊EventBus
@Override
protected void onDestroy() {
    //反注冊EventBus
    EventBus.getDefault().unregister(this);
    super.onDestroy();
}

//接收消息後的實作,4種不同的實作方法,根據項目實際需要選取
public void onEventMainThread(MyEventBus myEventBus) {
    String msg = "onEventMainThread收到了消息" + myEvent.getmMsg();
    textView.setText(msg);
    Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}

種不同方法實作的差別:
//onEvent:
如果使用onEvent作為訂閱函數,那麼該事件在哪個線程釋出出來的,
onEvent就會在這個線程中運作,也就是說釋出事件和接收事件線程在同一個線程。
使用這個方法時,在onEvent方法中不能執行耗時操作,如果執行耗時操作容易導緻事件分發延遲。

//onEventMainThread:
如果使用onEventMainThread作為訂閱函數,那麼不論事件是在哪個線程中釋出出來的,
onEventMainThread都會在UI線程中執行,接收事件就會在UI線程中運作,這個在Android中是非常有用的,
因為在Android中隻能在UI線程中跟新UI,是以在onEvnetMainThread方法中是不能執行耗時操作的。

//onEventBackground:
如果使用onEventBackgrond作為訂閱函數,
那麼如果事件是在UI線程中釋出出來的,那麼onEventBackground就會在子線程中運作,
如果事件本來就是子線程中釋出出來的,那麼onEventBackground函數直接在該子線程中執行。

//onEventAsync:
使用這個函數作為訂閱函數,那麼無論事件在哪個線程釋出,
都會建立新的子線程在執行onEventAsync.
           

(3) 發送消息

//發送消息界面無需注冊于反注冊
 EventBus.getDefault().post(new MyEvent("EventBus first Msg!!!"));