1

我正在尝试开发一个简单的媒体播放器来播放 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));
4

1 回答 1

4

我认为您应该使用服务在后台运行媒体所以您创建一个服务并将您的媒体代码放入其中并将其附加到启动和停止按钮可能是这样的:

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();
     }
}

之后,当使用方法按下开始按钮时启动该服务,并在 Activity 类startService中使​​用方法停止它stopService

于 2012-11-13T13:59:49.897 回答