paul_schaefer paul_schaefer - 1 year ago 100
Android Question

Android stop sounds

I am writing an alert app. When an alert is received, I want to stop all current sounds (like music) and play my alert sound. After the user has done something and the activity will be closed, the previous sounds should continue.

Thats the same like someone calls you. How can I achieve this behaviour?

Answer Source

You can request audio focus. Once you are done with your own audio, abandon audio focus so other apps can start playing sound again. You will be notified of other apps requesting audio focus too, thus being able to pause and resume your own sounds.

Requesting audio focus:

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

// Request audio focus for playback
int result = am.requestAudioFocus(afChangeListener,
                                 // Use the music stream.
                                 // Request permanent focus.

if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
    // Start playback.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download