Search code examples
androidbroadcastreceiverandroid-mediaplayer

How BroadcastReceiver can communicate with Service


How BroadCastReciever can communicate with service without binding?

I thought that it is good idea to use binder in BroadCastReceiver but after reading some info, i understood that it is not a good idea. I tried to find issue in stackoverflow, but all what i finded is:

Q:"BroadCastReciver + binder"

A:"No, it is bad idea."(without giving examples how to communicate with service without binder)


Solution

  • Solution - LocalBroadcastManager. Thanks to LocalBroadcastManager we can send broadcasts between different part of our app.

    SEND_BROADCAST

    LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(context);
            IntentFilter filter = new IntentFilter("com.onezero.EXAMPLE_ACTION");
            localBroadcastManager.registerReceiver(new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    Toast.makeText(context, "=(", Toast.LENGTH_SHORT).show();
                }
            }, filter);
    
            Intent sintent = new Intent("com.onezero.EXAMPLE_ACTION");
    
    
            localBroadcastManager.sendBroadcast(sintent);
    
    

    Receive Broadcasts

    LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
            IntentFilter filter = new IntentFilter("com.onezero.EXAMPLE_ACTION");
            localBroadcastManager.registerReceiver(new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    // DO WORK
                    setPlayPause(); //PAUSE MEDIAPLAYER IN MY CASE
                }
            }, filter);