Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send message from BroadcastReceiver to activity or fragment

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 fine.

Sometime, when my activity is running, i get some incoming call. the receiver runs & stores data to DB. UI wont get refreshed because it never knows about change in DB.

Here i need to manually tell from receiver that, if activity is running refresh screen. How to implement this process in android.

I'm slightly confused in this part

like image 665
Naruto Avatar asked Oct 28 '25 12:10

Naruto


1 Answers

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.

like image 198
Emanuel Moecklin Avatar answered Oct 31 '25 01:10

Emanuel Moecklin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!