Need a simple demo for only check whether backgrou

2019-09-05 19:18发布

This question already has an answer here:

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 from here study Link and made a demo code

Demo code is here but this is not giving me the O/P:

AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);

AudioManager.STREAM_MUSIC,AudioManager.AUDIOFOCUS_GAIN);
    int result = am.requestAudioFocus(new OnAudioFocusChangeListener() {

        @Override
        public void onAudioFocusChange(int focusChange) {
            if(//background Music is running )
            {}
            else{
                 //background Music is not running
            }
        }
    },AudioManager.STREAM_MUSIC,AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);

What is need to be add for what I want. Please help to make it east this thing.

1条回答
小情绪 Triste *
2楼-- · 2019-09-05 20:08

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)

OnAudioFocusChangeListener afChangeListener = new OnAudioFocusChangeListener() {
    public void onAudioFocusChange(int focusChange) {
        if (focusChange == AUDIOFOCUS_LOSS_TRANSIENT) {
            // another app took the stream temporarily
        } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
            // another app let go of the stream
        } else if (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.

查看更多
登录 后发表回答