androidaudiomediaandroid-audiomanager

Is there a system broadcast when media starts playing?


I would like my app to be notified whenever media starts playing on an Android device. I can't seem to find any system broadcast that is sent out when this happens. I know I can check with audiomanager.isMusicActive() but this would require me to poll constantly.

I also know you can request audioFocus and then listen for when you lose focus, but I don't necessarily want to request audio focus either!


Solution

  • You could use AudioManager#registerAudioPlaybackCallback() to register a callback that will be notified on playback events.

    // Variable for keeping track of current playback state
    private boolean mIsMediaPlaying = false;
    
    private class MyAudioPlaybackCallback extends AudioManager.AudioPlaybackCallback {
        @Override
        public void onPlaybackConfigChanged(List<AudioPlaybackConfiguration> configs) {
            // Iterate all playback configurations
            for (int i = 0; i < configs.size(); i++) {
                // Check if usage of current configuration is media
                if (configs.get(i).getAudioAttributes().getUsage() == AudioAttributes.USAGE_MEDIA) {
                    // Set is media playing to true since active playback was found
                    MainActivity.this.mIsMediaPlaying = true;
                    return;
                }
            }
            // Set is media playing to false since no active playback found
            MainActivity.this.mIsMediaPlaying = false;
        }
    }
    

    And then you can register the callback somewhere in your application.

    MyAudioPlaybackCallback playBackCallback = new MyAudioPlaybackCallback();
    AudioManager audioManager = this.getSystemService(AudioManager.class);
    audioManager.registerAudioPlaybackCallback(playBackCallback, null);
    

    I am not sure if AudioAttributes.getUsage() is the correct method for you, maybe you would like to use AudioAttributes.getContentType() to check for CONTENT_TYPE_MUSIC instead.