在Android 2.3.3中以睡眠/待机模式播放音乐
作者:互联网
我正在尝试开发一个简单的媒体播放器来播放Android 2.3.3的sdcard / music目录的mp3.问题是当我按下电源按钮或设备进入睡眠状态时,音乐会停止.通过谷歌搜索和搜索stackoverflow,我发现我需要使用唤醒锁定选项,但无论我做什么,当设备进入睡眠状态时音乐停止(在模拟器上按F7也会停止音乐).因为我已经打了很长时间,所以我想我会寻求帮助.我真诚地感谢任何意见.谢谢.这是我的代码:
FileInputStream fis = new FileInputStream(songList.get(0));
FileDescriptor fd = fis.getFD();
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.release();
mediaPlayer = null;
}
}
mediaPlayer = new MediaPlayer();
mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
mediaPlayer.setDataSource(fd);
mediaPlayer.prepare();
playPauseButton.setImageResource(android.R.drawable.ic_media_pause);
mediaPlayer.seekTo(songPosition);
mediaPlayer.start();
appMsg.setText(songList.get(0));
解决方法:
我认为你应该使用服务在后台运行媒体
因此,您创建一个服务并将您的媒体代码放入其中并将其附加到开始和停止按钮可能是这样的:
public class MediaPlayerService extends Service {
MediaPlayer myMediaPlayer;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
FileInputStream fis = new FileInputStream(songList.get(0));
FileDescriptor fd = fis.getFD();
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.release();
mediaPlayer = null;
}
}
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(fd);
mediaPlayer.prepare();
playPauseButton.setImageResource(android.R.drawable.ic_media_pause);
mediaPlayer.seekTo(songPosition);
appMsg.setText(songList.get(0));
}
@Override
public void onStart(Intent intent, int startid) {
myMediaPlayer.start();
}
@Override
public void onDestroy() {
myMediaPlayer.stop();
}
}
之后,当使用methodestartService按下开始按钮并在Activity类中使用methode stopService停止它时启动该服务
标签:playback,android,sleep,standby 来源: https://codeday.me/bug/20191001/1838425.html