I'm new to android app development and it's my first app. I'm building a music player, I have following method
public void playSong(int songIndex){
// Play song
mContext = getApplicationContext();
AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
OnAudioFocusChangeListener afChangeListener = new OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT){
mp.pause();
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
mp.start();
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
mp.stop();
}
}
};
// Request audio focus for playback
int result = am.requestAudioFocus(afChangeListener,
// Use the music stream.
AudioManager.STREAM_MUSIC,
// Request permanent focus.
AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// Start playback.
try {
mp.reset();
mp.setDataSource(songsList.get(songIndex).get("songPath"));
mp.prepare();
mp.start();
String songTitle = songsList.get(songIndex).get("songTitle");
songTitleLabel.setText(songTitle);
// Changing Button Image to pause image
btnPlay.setImageResource(R.drawable.btn_pause);
// set Progress bar values
songProgressBar.setProgress(0);
songProgressBar.setMax(100);
// Updating progress bar
updateProgressBar();
}
catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
when the song completes it should start playing the next song but it doesn't. Then I played switched to default media player and switch back to my app and it plays the app. I guess it has to do with the audio focus. How to determine if it already has focus or release the focus on completion. Thanks!!