MediaPlayerService的java.lang.IllegalStateException

时间:2018-07-27 10:47:19

标签: java android

当我单击“后退”按钮后返回时,我尝试播放音乐时出现错误“ java.lang.IllegalStateException”-但是为什么..?我注意到其他方法,例如player.isPlaying()或player.reset()也不起作用。如果有人已经有此问题,请帮助。美好的一天:)

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

活动分类:

@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类:

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

1 个答案:

答案 0 :(得分:0)

我必须更改onDestroy方法:

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