Search code examples
androidbroadcastreceiverandroid-service

one broadcast receiver with multiple action handling vs several broadcast receivers


I put a broadcast receiver inside my android service class. So far only one called "receiver". Is it better to have only one broadcast receiver with a selection statement in it (like if else if)? Can I put more than one broadcast receiver inside an android service class?

For example, this sample code is similar to what I work with. There is an 'else if' statement in it to handle two different intent broadcasts:

 public BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent){
        String action = intent.getAction();
    if(action.equals("com.test.AudioPlay")){
            // action for play
            Toast.makeText(AudioService.this, "play audio from service", Toast.LENGTH_LONG).show();
        }
        else if(action.equals("com.test.AudioPause")){
            // action for pause
            Toast.makeText(AudioService.this, "pause audio from service", Toast.LENGTH_LONG).show();
        }
    }

};

Solution

  • If you will use only one broadcast receiver with different action will be more efficient than different broadcast receivers for all the actions.

    You should bind the service with your activity as I read that you are trying to broadcast for start, pause and all functionality for music player. For more info about the boundservices you can refer the developer blog.