使用EventBus 3.0 报 Subscriber class com.example.test.MainActivity and its super classes have no public methods with the @Subscribe annotation

发布时间 2023-05-09 17:45:53作者: xiaowang_lj

 代码如下:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //订阅事件
        EventBus.getDefault().register(this);
        
        EventBus.getDefault().post(new MessageEvent("onCreate",0));

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消订阅
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void whenOnClick(){
        Toast.makeText(this, "收到事件", Toast.LENGTH_SHORT).show();
    }
}

原因:被注解 @Subscribe 标注的方法 参数没有对应的Event类型

解决方法:

方法参数加上对应的Event类型 参数的类型和发送的类型对应,当发送了多个类型时,注解方法只接收并处理与其发送的Event类型一致的事件

@Subscribe(threadMode = ThreadMode.MAIN)
    public void whenOnClick(MessageEvent messageEvent){
        Toast.makeText(this, "收到事件", Toast.LENGTH_SHORT).show();
    }