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

 代码如下:

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();
    }

 粘性事件

发送事件后再订阅事件也可以收到,发送时使用postSticky 方法

EventBus.getDefault().postSticky(new MessageEvent("onCreate",0));
需要指定 sticky = true  默认为false
@Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void whenOnClickSticky(MessageEvent messageEvent){
        Toast.makeText(this, "收到了事件"+messageEvent.getMessage(), Toast.LENGTH_SHORT).show();
    }

事件优先级

高优先级的事件优先于低优先级的事件,不管高低优先级,都会收到事件并处理,指定事件优先级使用  @Subscribe 的priority指定即可

@Subscribe(threadMode = ThreadMode.MAIN,priority = 2)

 

 
posted @ 2023-05-09 17:38  xiaowang_lj  阅读(370)  评论(0编辑  收藏  举报