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.
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
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)
Now you can register the listener and detect 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.