一、Otto简单介绍
OTTO是Square推出的库,地址:https://github.com/square/otto
先来看看otto的官方介绍
An enhanced Guava-based event bus with emphasis on Android support.Otto is an event bus designed to decouple different parts of your application while still allowing them to communicate efficiently.Forked from Guava, Otto adds unique functionality to an already refined event bus as well as specializing it to the Android platform.
OTTO基于Guava项目的Android支持库,如果你在Android程序开发的过程中想要不同的组件之间进行有效的通信可以使用这个库。通过otto库可以。
二、Otto简单使用
1、创建一个BUS的单例。
public class AppConfig {
private static final Bus BUS = new Bus();
public static Bus getInstance() {
return BUS;
}
}
2、在需要使用Otto的类中注册
在类创建好之后,或者需要重新注册的时候注册,一般在Activity的onCreate()或者onPause()方法中
AppConfig.getBusInstance().register(this);
3、定义订阅方法
@Subscribe
public void onWallpaperUpdate(MyObject obj) {
//对obj进行需要的逻辑处理
}
4、发送消息
AppConfig.getBusInstance().post(myobj);
5、解绑
注意在类销毁的时候或者暂时不需要再收消息的时候解绑,,一般在Activity的onDestroy()或者onResume()方法中
AppConfig.getBusInstance().unregister(this);
三、Otto源码解析
1、整体结构
otto的源码结构非常简单,所有类都包含