Android: MediaPlayer AUDIOFOCUS_LOSS & setOnErrorListener() issue

后端 未结 2 388
隐瞒了意图╮
隐瞒了意图╮ 2021-01-14 11:27

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

相关标签:
2条回答
  • 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:

      • Your focusChangeListener e.g. focusChangeListener.hashCode()
      • Current context object e.g. context.hashCode()
      • Current thread id e.g. 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.

    0 讨论(0)
  • 2021-01-14 12:20

    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.

    0 讨论(0)
提交回复
热议问题