I would like to prevent some of my code from executing only when music or videos are currently playing. How would I accomplish this using a broadcast receiver?
Asked
Active
Viewed 1.9k times
1 Answers
50
You don't need a broadcast receiver for this - AudioManager
is your friend:
AudioManager.isMusicActive()
does the job you want, have a closer look here for details: AudioManager
here is an example:
AudioManager manager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
if(manager.isMusicActive())
{
// do something - or do it not
}

DonGru
- 13,532
- 8
- 45
- 55
-
Hi Martin, Thanks for the quick reply. I tried your code but it states that "getSystemService is undefined for the type"
. I need to place your code in the broadcast receiver because that's were I need to prevent certain code from executing. Truly, Emad – Emad-ud-deen Sep 06 '11 at 18:56 -
3Hi Martin, I found out why the error was occurring. I needed to add the keyword: context before getSystemService and it worked. Truly, Emad – Emad-ud-deen Sep 06 '11 at 19:19
-
6Is there a way to detect the details of the music too? Song-name; artist etc? – Zen May 11 '15 at 16:01
-
This method starts the service if music is active. Can someone tell me how to start service when music player is opened? – Fiju Jan 15 '17 at 14:53
-
2I don't know why but in my case _manager.isMusicActive()_ is always true even if there is not active music player. – dazed'n'confused Jan 24 '19 at 05:55