mbauer
mbauer

Reputation: 344

MusicPlayer crashes on click the back button

I made a simple music player which can play some songs in the background. Going to the homescreen and reopen the app through notification works as well.

The only Problem I have is that if I press the back button(going to parent activity) in the music player activity my app crashes. There are two classes, the activity MP3Player.java and the service MP3Service.jave.

I am getting the following error:

java.lang.RuntimeException: Unable to destroy activity {package/package.MP3Player}: java.lang.IllegalArgumentException: Service not registered: package.MP3Player$1@b135b300

Do you know any advide? Thanks in advance!

EDIT1: I bound my player like this in my player activity: MP3Player.java(Activity)

playIntent = new Intent(this, MP3Service.class);
bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
startService(playIntent);

I used this tutorial and modified it.

EDIT 3: Now I get this error:

java.lang.RuntimeException: Unable to stop service package.MP3Service@b13a6f80: java.lang.IllegalStateException

MP3Service.java

public void onCreate() {
    super.onCreate();
    songPosn = 0;
    player = new MediaPlayer();
    initMusicPlayer();
}

public void initMusicPlayer() {
    player.setAudioStreamType(AudioManager.STREAM_MUSIC);
}

...

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

public void setList(ArrayList<Song> theSongs) {
    songs = theSongs;
}

public class MusicBinder extends Binder {
    MP3Service getService() {
        return MP3Service.this;
    }
}

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

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

public void playSong() {
    player.reset();

    Song playSong = songs.get(songPosn);

    try {
        player.setDataSource(getApplicationContext(),
                Uri.parse(playSong.getPath()));
    } catch (Exception e) {
        Log.e("MUSIC SERVICE", "Error setting data source", e);
    }
    player.prepareAsync();
}

public void pauseMusic() {
    if (player.isPlaying()) {
        player.pause();
        length = player.getCurrentPosition();
    }
}

public void resumeMusic() {
    if (player.isPlaying() == false) {
        player.seekTo(this.length);
        player.start();
    } else {
        Toast.makeText(getApplicationContext(),
                "Please select a song to play", Toast.LENGTH_LONG).show();
    }
}

public void stopMusic() {
    player.stop();
    player.release();
    player = null;
}

// set the song
public void setSong(int songIndex) {
    songPosn = songIndex;

}

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

@Override
public void onDestroy() {
    super.onDestroy();
    if (player != null) {
        try {
            player.stop();
            player.release();
        } finally {
            player = null;
        }
    }
}

MP3Player.java

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mp3_player);
    getActionBar().setDisplayHomeAsUpEnabled(true);

    songList = getSongList();

    listAdapter = new PlayListAdapter(this, songList);
    listMusic.setAdapter(listAdapter);

    listMusic.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int pos,
                long arg3) {
            currentSongPos = pos;
            musicSrv.setSong(currentSongPos);
            musicSrv.playSong();
        }
    });

}

private ServiceConnection musicConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        MusicBinder binder = (MusicBinder) service;
        musicSrv = binder.getService();
        musicSrv.setList(songList);
        musicBound = true;
    }

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

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


...

protected void onDestroy() {
    if (musicBound) {
        stopService(playIntent);
        unbindService(musicConnection);
        musicSrv = null;
    }
    super.onDestroy();
}

Upvotes: 1

Views: 495

Answers (1)

Andrea C.
Andrea C.

Reputation: 109

Service not registered means it wasn't bound to service during unbindService() call.

Read about service lifecycle on : API Guide: Services

EDIT:

Try to add:

protected void onDestroy() {
  if(musicBound){
      stopService(playIntent);
      unbindService(musicConnection);
      musicSrv=null;
  }
  super.onDestroy();
}

EDIT 2:

Sorry my fault, you need to call first stopService() and then unbindService()

The Android documentation for stopService() states:

Note that if a stopped service still has ServiceConnection objects bound to it with the BIND_AUTO_CREATE set, it will not be destroyed until all of these bindings are removed. See the Service documentation for more details on a service's lifecycle.

Upvotes: 1

Related Questions