EventBus 3.0 annotationprocess

加速模式:
“`
public class MyApplication extends Application {

@Override
public void onCreate() {
super.onCreate();
// 启用EventBus3.0加速功能
EventBus.builder().addIndex(new MyEventBusIndex()).installDefaultEventBus();

}
}
“`

使用:
“`
监听者(需要改变的Activity中)
onCreate()中:
mBuild = EventBus.builder().build();
mBuild.register(this);
onDestory()中:
mBuild.unregister(this);

“`
回掉的接口: 可以随便取名
“`
@Subscribe(threadMode = ThreadMode.MAIN)。//运行所在的线程
public void onRefUserInfo(ChangeUserImg bean) {
mSdHeadView.setImageURI(bean.getAvatar());
}
“`

触发事件:
“`
EventBus.getDefault().post(new ChangeUserImg(“changeData”));
“`

封装的消息通知类 ChangeUserImg 可以随便取名
“`
public class ChangeUserImg {

private String avatar;

public ChangeUserImg(String avatar) {
this.avatar = avatar;
}

public String getAvatar() {
return avatar;
}
}

“`

utils工具类:
“`
public class EventBusUtils {

private static final String TAG = “EventBusUtils”;
private EventBusUtils() {
}

/**
* 注册EventBus
*
* @param subscriber 订阅者对象
*/
public static void register(Object subscriber) {
if (!EventBus.getDefault().isRegistered(subscriber)) {
Log.e(TAG, “register: 注册成功”);
EventBus.getDefault().register(subscriber);
} else {
Log.e(TAG, “register: 注册失败”);
}
}

/**
* 取消注册EventBus
*
* @param subscriber 订阅者对象
*/
public static void unregister(Object subscriber) {
EventBus.getDefault().unregister(subscriber);
}

/**
* 发布订阅事件
*
* @param event 事件对象
*/
public static void post(Object event) {
EventBus.getDefault().post(event);
}

/**
* 发布粘性订阅事件
*
* @param event 事件对象
*/
public static void postSticky(Object event) {
EventBus.getDefault().postSticky(event);
}

/**
* 移除指定的粘性订阅事件
*
* @param eventType class的字节码,例如:String.class
*/
public static void removeStickyEvent(Class eventType) {
T stickyEvent = EventBus.getDefault().getStickyEvent(eventType);
if (stickyEvent != null) {
EventBus.getDefault().removeStickyEvent((T) stickyEvent);
}
}

/**
* 移除所有的粘性订阅事件
*/
public static void removeAllStickyEvents() {
EventBus.getDefault().removeAllStickyEvents();
}

/**
* 取消事件传送
*
* @param event 事件对象
*/
public static void cancelEventDelivery(Object event) {
EventBus.getDefault().cancelEventDelivery(event);
}
}
“`

EventBus.getDefault() 单例模式: 懒汉式

Register: 获取订阅者的类对象,找到订阅类中的所有订阅方法信息。EventAnnotationProcess 注解处理器 生成的MyeventBusIndex获取。或者通过反射获取订阅方法信息。

* EventAnnotationProcess 编译期间就解析所有@Subscriber()注解,处理所包含的信息,生成java类保存所有订阅者关于订阅信息。比运行时候通过反射更快。

Advertisements
EventBus 3.0 annotationprocess

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s