Skip to content Skip to sidebar Skip to footer

Need A Simple Demo For Only Check Whether Background Music Running Or Not?

I need a simple demo, In which I want to check whether the music is running in the background or not? And also does not effected on the music which is running in Background I read

Solution 1:

The current code you've posted appears to be that you are actually requesting to use the STREAM_MUSIC stream rather than detecting it. I believe you may have two options for this.

I haven't tried is this method, but it sounds like AudioManager.isMusicActive() may work for you.

From this page, it says

Checks whether any music is active.

Returns true if any music tracks are active.

Your other option is to use AudioManager.OnAudioFocusChangeListener. You must first create this listener and then register it to detect changes. This means your app would need to be running in the background before another app started using the stream.

Create a listener (examples from http://developer.android.com/training/managing-audio/audio-focus.html)

OnAudioFocusChangeListenerafChangeListener=newOnAudioFocusChangeListener() {
    publicvoidonAudioFocusChange(int focusChange) {
        if (focusChange == AUDIOFOCUS_LOSS_TRANSIENT) {
            // another app took the stream temporarily
        } elseif (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
            // another app let go of the stream
        } elseif (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
            // another app took full control of the stream
        }
    }
};

Now you can register the listener and detect changes

int result = am.requestAudioFocus(afChangeListener,
                                 // Use the music stream.
                                 AudioManager.STREAM_MUSIC,
                                 // Request permanent focus.
                                 AudioManager.AUDIOFOCUS_GAIN);

if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
    // You successfully took control of the stream and can detect any future changes
}

This isn't a terribly elegant solution since you will most likely take away the music stream from other apps. It depends on your use case, but it may be a starting point.

Post a Comment for "Need A Simple Demo For Only Check Whether Background Music Running Or Not?"