Create this class to play a sound file on android: link
The problem is that when running this application on my cell phone it stops instantly. When reviewing the logcat it appears this error.
Using the android studio debugger I was able to trace the error to line 52:
int result = mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener, AudioManager .STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
Investigate the requestAudioFocus function and try to apply it as the google documentation says so modify the activity to match the documentation: link
Now the error occurs on line 58:
AudioAttributes playbackAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_GAME)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build();
Note: Android studio showed the error " Call requires API level 26 (current min is 15) " so I had to add " @TargetApi (Build .VERSION_CODES.O) "on line 50.
In the logcat the error appears when running this version of the activity.
The question is: What is the correct way to use the requestAudioFocus () function?
Note: The Android version of the cell phone I am using to test the application is 4.2.2 and according to Google Documentation The API level it uses is 17 (JELLY_BEAN_MR1)
Note 2: The app is "inspired" by this repository . In case you want to run this application you should modify the file build.gradle and add the " google () " function on line 18.