EventBus使用说明及NoClassDefFound错误解决

一、EventBus使用

一直听说过EventBus的大名,在很多第三方SDK的源码里都能看到它的身影,以为很复杂很难,一直没有接触,最近朋友推荐一篇博客:

EventBus使用详解

看了才发现原来EventBus这么简单,简单三步就可以在项目中使用。

1.build.gradle中加入
compile 'org.greenrobot:eventbus:3.0.0'
2. 任意类中注册EventBus
public class BaseActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);//注册EventBus
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//反注册EventBus
    }
    ...
    @Subscribe
    public void onEvent(AnyEvent event){
        //接收事件用
    }
}
3. 新建事件类
public class AnyEvent{
        private String msg;
        public AnyEvent(String msg) { this.msg = msg; }
        public String getMsg() { return msg;}
}
4. 任意逻辑中发送事件
public class MainActivity extends BaseActivity {
      ...
      public void sentEvent(String msg){
          AnyEvent event=new AnyEvent(msg);
          EventBus.Default().post(event);//发送事件
      }
}
这样就可以使用了!
下面是我总结的EventBus的两个最大的优点:

1.APP的事件传递更方便直接,免去回调、广播的麻烦,耦合性更低;
2.每个事件都有一个独立类,可以更清晰地实现业务逻辑。

二、注册时NoClassDefFound错误

在Activity中注册时候会出现以下错误:

EventBus使用说明及NoClassDefFound错误解决_第1张图片
EventBus注册错误:NoClassDefFoundError

这个错误首先详见Github的问题解释:
Stops NoClassDefFound exceptions on EventBus#register(Object)
EventBus使用说明及NoClassDefFound错误解决_第2张图片
EventBus 注册错误 GitHub讨论

上面说不能在两个参数的onCreate里面注册EventBus

@Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        EventBus.getDefault().register(this);//这里注册会报错NoClassDefFoundError
}

但我命名是在一个onCreate(Bundle savedInstanceState)中注册的也是报这个错,怎么回事?

在我快折腾疯了的时候发现原来我在BaseActivity中重写了onCreate(Bundle savedInstanceState, PersistableBundle persistentState):


EventBus使用说明及NoClassDefFound错误解决_第3张图片
BaseActivty重写OnCreate

尝试删掉就可以正常注册EventBus了...

原来不但不能在里面注册,连重写onCreate(Bundle savedInstanceState, PersistableBundle persistentState)都不行

你可能感兴趣的:(EventBus使用说明及NoClassDefFound错误解决)