java.lang.IllegalStateException with MediaPlayerService

When I come back after click the back button and I try to play music I have error ‘java.lang.IllegalStateException’ – but why..? I noticed that others method like player.isPlaying() or player.reset() didn’t work too. If somebody had already this problem – please help. Nice day 🙂

java.lang.IllegalStateException
    at android.media.MediaPlayer.prepareAsync(Native Method)

Activity class:

@Override
protected void onStart() {
    super.onStart();
    playIntent = new Intent(this, MediaPlayerService.class);
    bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
    startService(playIntent);

}

@Override
protected void onDestroy() {
    super.onDestroy();

    if(musicConnection!=null){
        unbindService(musicConnection);
    }
}

private ServiceConnection musicConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        MediaPlayerService.LocalBinder musicBinder = (MediaPlayerService.LocalBinder) service;
        musicService = musicBinder.getService();
        musicBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        musicBound = false;
    }
};

MusicService class:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return Service.START_NOT_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
    return iBinder;
}

@Override
public boolean onUnbind(Intent intent) {
    player.stop();
    player.reset();
    player.release();
    return false;
}

@Override
public void onPrepared(MediaPlayer mp) {
    mp.start();
}

@Override
public void onCreate() {
    super.onCreate();
    setSong(0);
    player = new MediaPlayer();
    initMediaPlayer();
}

public void initMediaPlayer(){
    player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
    player.setAudioStreamType(AudioManager.STREAM_MUSIC);
    player.setOnPreparedListener(this);
    player.setOnCompletionListener(this);
    player.setOnErrorListener(this);
}

public void playSong(){
    try{
        player.reset();
        Song playSong = songList.get(songPos);            
        long currSong = playSong.getId();
        Uri trackUri = ContentUris.withAppendedId(
            android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            currSong);
        player.setDataSource(getApplicationContext(), trackUri);
    }catch(Exception e){
        Log.e("MUSIC SERVICE", "Error setting data source", e);
    }
    player.prepareAsync();
}

Answer

I had to change the onDestroy method on:

@Override
protected void onDestroy() {
stopService(playIntent);
musicService = null;
super.onDestroy();
}

Leave a Reply

Your email address will not be published. Required fields are marked *