Activity跳轉經過EventBus傳值問題

根據阿里發佈的Android開發規範:下載地址:https://102.alibaba.com/downloadFile.do?file=1520478361732/Android_v9.pdfide

Activity 間的數據通訊,對於數據量比較大的,避免使用 Intent + Parcelable
的方式,能夠考慮 EventBus 等替代方案,以避免形成 TransactionTooLargeException。post

A界面 跳轉到 B界面,傳對象。this

可是用普通的EventBus方法【 EventBus.getDefault.post(xx)  】是存在問題的:問題是因爲主界面還未建立,用於接收的EventBus還未註冊,即發佈者發了消息,但訂閱者還未產生(通常消息的處理邏輯是先註冊訂閱,後接收),這樣沒有收到消息固然沒法響應操做。spa

EventBus的粘性事件能夠解決這樣的問題。code

基本使用方法:對象

1,A界面 粘性事件的發佈:blog

EventBus.getDefault().postSticky(barcodeEventBean,"registerData");
//跳轉到接收message的界面
Intent intent = new Intent(A.this, B.class);
startActivity(intent);

 

2,B界面 粘性接收器的註冊:事件

//註冊EventBus的粘性事件
EventBus.getDefault().registerSticky(this);

3,B界面 接收A界面傳值的方法開發

@Subscriber(tag = "registerData")
    public void getRegisterBarcode(EventBean.BarcodeEventBean barcodeEventBean) {
        if(barcodeEventBean != null && barcodeEventBean.getBarcodeList() != null){
          Log.e(barcodeEventBean.toString)
        }

    }

4,B界面在銷燬的時候,取消註冊rem

@Override
    protected void onDestroy() {
        super.onDestroy();
       EventBus.getDefault().removeStickyEvent(EventBean.BarcodeEventBean.class,"registerData");
    }
over
相關文章
相關標籤/搜索