-->

How to use the EventBus onEvent method?

2019-07-15 10:21发布

问题:

I'm using EventBus in my Android application. In my mainActivity, I have this handler method which sends live data to the EventBus as follows:

private final Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case TGDevice.MSG_STATE_CHANGE:
                EventBus.getDefault().postSticky(msg.arg1);
                ...

I'm using Fragments class and I need to receive the message from the handler.

I have registered the Fragment class in the onCreateView method as follows:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_data_log, container, false);
    EventBus.getDefault().register(this);
    tv = (TextView) view.findViewById(R.id.tv);
}

public void onEvent(Message message){
    tv.setText("Signal" + message);
}

And I have the onEvent method which is suppose to be called when there is an Event. Unfortunately, this method is never called. I thought it might be method to be overridden but it doesn't seem to be.

What do i need to do to read from messages from the EventBus?

Also, in debugging modes, where can I see the number of threads being created? (I'm using Android Studio)

回答1:

Unfortunately, this method is never called

That is because your onEvent() takes a Message, and (presumably) you are not posting a Message. You are posting whatever arg1 is.

Also, in debugging modes, where can I see the number of threads being created? (I'm using Android Studio)

Go into the Android Debug Monitor (Tools > Android > Android Debug Monitor from the main menu), and there's a threads view in DDMS inside of there.