安卓開發EventBus框架
使用場景
不同類間數據過渡傳遞更新
EventBus是一款針對Android優化的發布/訂閱事件匯流排。主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,線程之間傳遞消息.優點是開銷小,代碼更優雅。以及將發送者和接收者解耦。
1. Event:事件
2. Subscriber:事件訂閱者,接收特定的事件
3. Publisher:事件發布者,用於通知Subscriber有事件發生
基本框架搭建
1、添加依賴
compile org.greenrobot:eventbus:3.0.0
2、自定義一個類,可以是空類
public class AnyEventType {
public AnyEventType(){}
}
也可以是含有參數的類
public class FirstEvent {
private String mMsg;
public FirstEvent(String msg) {
// TODO Auto-generated constructor stub
mMsg = msg;
}
public String getMsg(){
return mMsg;
}
}
3、在要接收消息的頁面註冊
3.1接受消息實現(四個函數)
onEvent:
如果使用onEvent作為訂閱函數,那麼該事件在哪個線程發布出來的,onEvent就會在這個線程中運行,也就是說發布事件和接收事件線程在同一個線程。使用這個方法時,在onEvent方法中不能執行耗時操作,如果執行耗時操作容易導致事件分發延遲。因為它會阻塞事件的傳遞,甚至有可能會引起ANR。 onEventMainThread:
如果使用onEventMainThread作為訂閱函數,那麼不論事件是在哪個線程中發布出來的,onEventMainThread都會在UI線程中執行,接收事件就會在UI線程中運行,這個在Android中是非常有用的,因為在Android中只能在UI線程中跟新UI,所以在onEvnetMainThread方法中是不能執行耗時操作的。
事件的處理會在UI線程中執行。事件處理時間不能太長,長了會ANR的。 onEventBackground:
如果使用onEventBackgrond作為訂閱函數,那麼如果事件是在UI線程中發布出來的,那麼onEventBackground就會在子線程中運行,如果事件本來就是子線程中發布出來的,那麼onEventBackground函數直接在該子線程中執行。 onEventAsync:
使用這個函數作為訂閱函數,那麼無論事件在哪個線程發布,都會創建新的子線程在執行onEventAsync.
3.2 框架執行
3.2.1註冊監聽
在onCreate裡面 EventBus.getDefault().register(this);
3.2.2 接收消息處理
使用EventBus中最常用的onEventMainThread()函數來接收消息
public void onEventMainThread(FirstEvent event) {
String msg = "onEventMainThread收到了消息:" + event.getMsg();
Log.d("harvic", msg);
tv.setText(msg);
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
3.2.3 OnDestroy()解除註冊
EventBus.getDefault().unregister(this);//解除註冊EventBus
4、發送消息
4.1 發送消息
EventBus.getDefault().post(new FirstEvent("FirstEvent btn clicked"));
推薦閱讀:
※框架到底是個什麼東西?
※無為文件管理術之「框架思維」
※2017年度最流行的十大中國開源軟體
※想要開發自己的PHP框架需要那些知識儲備?
※Retrofit 實現分析