How to pass data from BroadcastReceiver to Activity without in onCreate()

后端 未结 3 1808
陌清茗
陌清茗 2021-01-21 01:56

I have a serious issue about passing data from BroadcastReceiver to an Activity. Let see my issue carefully. I have a class PhoneStateReceiver ex

3条回答
  •  孤街浪徒
    2021-01-21 02:42

    There is a very simple design pattern you can use here to ease communication between your classes and also decouple your code: publisher/subscriber. My favorite library for this is EventBus:

    First, add to your build.gradle file:

    compile 'org.greenrobot:eventbus:3.0.0'
    

    Then, create a simple POJO - Plain Old Java Object like this:

    public class OnReceiverEvent{
       private String phoneNumber;
    
       public OnReceiverEvent(String phone){
          this.phoneNumber = phone;
       }
    
       public String getPhoneNumber(){
          return phoneNumber;
       }
    }
    

    Next, by making your Receiver class a publisher, and your Activity a subscriber, you should be able to easily pass the information to your activity like this:

    //inside your PhoneStateReceiver class when you want to pass info
    
    EventBus.getDefault().post(new OnReceiverEvent(phoneNumber));
    

    Next, inside your activity, simply do this:

    //onStart
    @Override
    public void onStart(){
       super.onStart();
       EventBus.getDefault().register(this);
    }
    
    //onStop
    @Override
    public void onStop(){
       super.onStop();
    
       EventBus.getDefault().unregister(this);
    }
    

    Finally, handle the posted data i.e phoneNumber value:

    @Subscribe
    public void onPhoneNumberReceived(OnReceiverEvent event){
       //get the phone number value here and do something with it
    
       String phoneNumber = event.getPhoneNumber();
    
       //display or something?
    }
    

    UPDATE

    If you have another Event that you want this activity to subscribe to, simply create a method like you did in the first one using the @Subscribe annotation.

    @Subscribe
    public void onSomeOtherEvent(EventClassName event){
       //get the variables here as usual;
    }
    

    This is the easiest way to pass the data from your receiver to your activity without having to worry about starting the activity over and over!

    I hope this helps and good luck!

提交回复
热议问题