How to send message from BroadcastReceiver to activity or fragment

后端 未结 2 1343
深忆病人
深忆病人 2021-01-23 06:28

I have a receiver, it does call details saving task like storing incoming call, outgoing call etc.. all these details goes to sqlite DB. If my activity is not running, then its

相关标签:
2条回答
  • 2021-01-23 06:47

    You can use a LocalBroadcastManager to send a local broadcast to your Activity (more efficient and more secure than using a global broadcast):

    Intent intent = new Intent(action);
    LocalBroadcastManager mgr = LocalBroadcastManager.getInstance(context);
    mgr.sendBroadcast(intent);
    

    http://developer.android.com/reference/android/support/v4/content/LocalBroadcastManager.html

    Your Activity would have to register a BroadcastReceiver in onStart and unregister it in onStop:

    private BroadcastReceiver mBroadcastReceiver;
    
    mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // do your thing
        }       
    };
    
    LocalBroadcastManager mgr = LocalBroadcastManager.getInstance(this);
    mgr.registerReceiver(mBroadcastReceiver, new IntentFilter(action));
    

    in onStop:

    mgr.unregisterReceiver(mBroadcastReceiver)
    

    Now that's the official Android way to do it. I most certainly prefer to use an event/message bus like Otto or EventBus (https://github.com/greenrobot/EventBus). You can use those to broadcast messages/events across different components in your app. The advantage is you don't need access to a Context (like you do when using Broadcasts), it's faster and it forces the developer to object oriented programming (since the events are always objects). Once you start using an event bus you'll never look back to local broadcasts and you'll replace many of the sometimes messy observer / listener patterns used across your app.

    0 讨论(0)
  • 2021-01-23 06:53

    You can create a BroadcastReceiver inside an activity. Register it in onResume() and unregister it in onPause(). Whenever your other receiver receives a broadcast, send a broadcast to this receiver too. If the activity is running(i.e. on front), the broadcast will be received. Do whatever you want in its onReceive().

    Example:

    BroadcastReceiver br = new BroadcastReceiver() {
    
            @Override
            public void onReceive(Context context, Intent intent) {
                //Do stuff
            }
        };
    

    Also override methods:

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(br);
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(br, new IntentFilter("intent_filter"));//Use any string for IntentFilter you like
    }
    

    You can update fragments from activiy by creating methods inside fragment and access them from Fragment object inside activity.

    0 讨论(0)
提交回复
热议问题