問題
比如界面MainActivity向界面SecondActivity發(fā)送消息時,界面S調(diào)用接收方法,可以接收界面M發(fā)送的消息,輸出臺log可以打印出消息內(nèi)容,但是無法更新UI。
MainActivity
Button eventBus= (Button) findViewById(R.id.eventbus);
RxView.clicks(eventBus)
.throttleFirst(1,TimeUnit.SECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Object>() {
@Override
public void accept(@NonNull Object o) throws Exception {
EventBus.getDefault().postSticky(new MessageEvent("MainActivity:this is Sticky"));
startActivity(SecondActivity.class);
}
});'
SecondActivity
@Override
@org.greenrobot.eventbus.Subscribe
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UtilsLog.i("主線程Id="+Thread.currentThread().getId()+",主線程名字="+Thread.currentThread().getName());
setContentView(R.layout.activity_second);
EventBus.getDefault().register(this);
initView();
}
private void initView() {
show= (TextView) findViewById(R.id.result);
show.setText("沉夢昂志");
}
@org.greenrobot.eventbus.Subscribe(sticky=true,threadMode = org.greenrobot.eventbus.ThreadMode.MAIN)
public void receiveMainActivity(MessageEvent event){
String result=event.getMessage();
show.setText(result);
}
分析問題
如果不仔細看代碼的話,這樣寫的話感覺沒問題。但是會出現(xiàn)一個問題,就是界面S的TextView一直不會更新,不會顯示界面M發(fā)送的消息內(nèi)容。其實問題就是在界面S,訂閱消息事件的代碼寫錯位置了,EventBus.getDefault().register(this);這句代碼放在initView()之前,造成的結(jié)果就是界面的控件還未初始化,就接收消息了,界面無法更新UI,也就是TextView還未初始化。
解決問題
只需要把EventBus.getDefault().register(this)放在最后就行了。
@Override
@org.greenrobot.eventbus.Subscribe
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
initView();
EventBus.getDefault().register(this);
}