Android知识Android 开发技术分享程序员

【开源框架】EventBus 消息总线使用

2017-06-17  本文已影响278人  dongbingliu
image.png

开源框架 —> EventBus 消息总线框架使用

1. 前言

OTA模块用到消息总线框架EventBus,经过对比handler,项目中消息比较多,使用EventBus框架,便于统一管理

EventBus是一款针对Android优化的发布/订阅事件总线。主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,线程之间传递消息.优点是开销小,代码更优雅。以及将发送者和接收者解耦

EventBus 框架类库 Github
源码:https://github.com/greenrobot/EventBus

2. 实战

2.1 基本使用方法

(1) 自定义一个消息类

public class MyEventBus{
   public static final int JUMP_TO_NETWORKSETTINGS = 0x01;
    public static final int RETURN_TO_SECONDPAGER = 0x02;
    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种不同的实现方法,根据项目实际需要选取
@Subscribe(threadMode = ThreadMode.MAIN)  
public void onMessageEvent(MessageEvent event) {/* Do something */};

(3) 发送消息

//发送消息界面无需注册于反注册
 EventBus.getDefault().post(new MyEvent("EventBus first Msg!!!"));

ThreadMode 四种线程实现控制

1. ThreadMode: POSTING

// Called in the same thread (default)(与Post保持一致的线程)
// ThreadMode is optional here
@Subscribe(threadMode = ThreadMode.POSTING)
public void onMessage(MessageEvent event) {
    log(event.message);
}

2. ThreadMode: MAIN

// Called in Android UI's main thread(UI 线程)
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessage(MessageEvent event) {
textField.setText(event.message);
}

3. ThreadMode: BACKGROUND

// Called in the background thread(post 主线程,新开线程接收消息,post非主线程,使用post线程)
@Subscribe(threadMode = ThreadMode.BACKGROUND)
public void onMessage(MessageEvent event){
    saveToDisk(event.message);
}

4. ThreadMode: ASYNC

// Called in a separate thread(直接新开线程)
@Subscribe(threadMode = ThreadMode.ASYNC)
public void onMessage(MessageEvent event){
    backend.send(event.message);
}

参考Github 开发描述:http://greenrobot.org/eventbus/documentation/delivery-threads-threadmode/

上一篇下一篇

猜你喜欢

热点阅读