天天看點

Android 的Otto插件的使用

otto 架構就是事件分發總線.

otto 下載下傳位址:http://square.github.io/otto/

在沒有用 Otto之前,Activity 和Fragment 之間的互動很麻煩.如果是一般的一對一互動,其實還算好.

最怕是Fragment 被多個 Activity 引用的時候,就要針對不同的頁面做處理.

在用了 Otto 之後,發現這一切都不是問題了.

解耦度大大的提升了.

對于 Otto 是什麼東西.其實在百度上可以查詢到.

在這裡,我就隻簡單的描述它的原理.

其實 Otto 說白了,就是一個根據觀察者模式實作的一個開源插件.

它是根據你的入參和出參判斷,的一個觀察者模式插件.

具體可以看(http://www.jianshu.com/p/c8ff4a999a28)

下面兩個基本類是我對 Otto 的基本封裝.

首先是 OttoProvider 是 Otto的主體,消息依賴它去傳輸.

public  final  class OttoProvider {

    private static final Bus BUS = new Bus();

    public static Bus getInstance() {
        return BUS;
    }

    private OttoProvider() {

    }
}      

接着,OttoMessage 是我個人封裝的 參數類型.(當然,這個類型你也可以自己去封裝)

public class OttoMessage implements Parcelable {
    public int what;
    public int arg1;
    public int arg2;
    public Object obj;

    private static final Pools.SynchronizedPool<OttoMessage> sPool =
            new Pools.SynchronizedPool(10);

    public static OttoMessage obtain() {
        OttoMessage instance = sPool.acquire();
        return (instance != null) ? instance :  new SoftReference<>(new OttoMessage()).get();
    }

    public void recycle() {
        sPool.release(this);
    }


    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(this.what);
        dest.writeInt(this.arg1);
        dest.writeInt(this.arg2);
        dest.writeValue(this.obj);
    }

    private OttoMessage() {
    }

    protected OttoMessage(Parcel in) {
        this.what = in.readInt();
        this.arg1 = in.readInt();
        this.arg2 = in.readInt();
        this.obj = in.readValue(Objects.class.getClassLoader());
    }

    public static final Parcelable.Creator<OttoMessage> CREATOR = new Parcelable.Creator<OttoMessage>() {
        public OttoMessage createFromParcel(Parcel source) {
            return new OttoMessage(source);
        }

        public OttoMessage[] newArray(int size) {
            return new OttoMessage[size];
        }
    };
}