Example: Communication between Activity and Service using Messaging

前端 未结 9 665
既然无缘
既然无缘 2020-11-22 00:06

I couldn\'t find any examples of how to send messages between an activity and a service, and I have spent far too many hours figuring this out. Here is an example project fo

9条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 00:51

    I have seen all answers. I want tell most robust way now a day. That will make you communicate between Activity - Service - Dialog - Fragments (Everything).

    EventBus

    This lib which i am using in my projects has great features related to messaging.

    EventBus in 3 steps

    1. Define events:

      public static class MessageEvent { /* Additional fields if needed */ }

    2. Prepare subscribers:

    Declare and annotate your subscribing method, optionally specify a thread mode:

    @Subscribe(threadMode = ThreadMode.MAIN) 
    public void onMessageEvent(MessageEvent event) {/* Do something */};
    

    Register and unregister your subscriber. For example on Android, activities and fragments should usually register according to their life cycle:

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }
    
    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }
    
    1. Post events:

      EventBus.getDefault().post(new MessageEvent());

    Just add this dependency in your app level gradle

    compile 'org.greenrobot:eventbus:3.1.1'
    

提交回复
热议问题