我是 android 应用程序开发的新手,这是我的第一个应用程序。我正在构建一个音乐播放器,我有以下方法
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();
}
}
}
当歌曲完成时,它应该开始播放下一首歌曲,但它没有。然后我播放切换到默认媒体播放器并切换回我的应用程序并播放应用程序。我想这与音频焦点有关。如何确定它是否已经具有焦点或释放完成的焦点。谢谢!!