androidsleepplaybackstandby

Playing music in sleep/standby mode in Android 2.3.3


I am trying to develop a simple media player to play mp3's of the sdcard/music directory for Android 2.3.3. The problem is when I hit the power button or when the device goes to sleep, the music stops. From googling, and searching stackoverflow, I found that I need to use the wake lock options, but no matter what I do, the music stops when the device goes to sleep (Pressing F7 on the emulator stops the music as well). Since I've been fighting this for way too long, I thought I'd ask for help. I would sincerely appreciate any input. Thanks. Here's my code:

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

Solution

  • I think you should run the media in background using services So you create a service and put your media code in it and attach it to start and stop buttons maybe somthing like this :

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

    After that you start that service when a start button is pressed using methodestartService and stop it using methode stopService in your Activity class