I\'m creating a music player app.
In that I am checking if my application loses AudioFocus then the playback will stop. But this is raising one issue that when I pla
I had similar issue, I strongly suspect that your focusChangeListener
is recreated somewhere in your program so you request focus on different instance of focusChangeListener
. Are you defining it from a service or activity?
The idea is to maintain a single copy of your focusChangeListener
that you pass to requestAudioFocus()
and abandonAudioFocus()
; otherwise the AudioManager will consider the request from different source, which can cause the app can lose focus to itself.
You should know that calling requestAudioFocus()
on the same listener object many times does register it only once and calling abandonAudioFocus()
one time is sufficient to release the audio focus.
Few suggestions that can solve your problem:
Try to define focusChangeListener
as static object and see if help.
If your listener is registered in Activity, consider to move to a service so the listener can survive longer.
To debug this issue, it is very helpful to log the following ** whenever ** you request or abandon focus to ensure that you have, to ensure that you are dealing with the same instance:
focusChangeListener.hashCode()
context.hashCode()
Thread.currentThread().getId()
For example:
Log.d(TAG, String.format("Request audio focus: thread id = %s, context = %s, listener = %s",Thread.currentThread().getId(),context.hashCode(),focusChangeListener hashCode())
Edit:
Using application context i.e. getApplicationContext()
can solve the issue as well.
Unfortunately IllegalStateExceptions don't trigger the OnErrorListener call. You will have to try/catch around portions of your code for IllegalStateExceptions where they may be triggered.