0

I'm trying to make a music player. To do that I'm creating a service that manages a MediaPlayer object and plays the songs. But every time I reopen my music application it starts a new Service and keeps playing two songs simultaneously. How can I make my Activity bind to the already running service?

I noticed that when I don't call unbindService (...) in the OnStop() method my application runs OK. But I don't know if its right to not unbind when the activity stops.

I'm binding like that:

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

    Intent service = new Intent(this,MyService.class);

    bindService(service, mConnection, Context.BIND_AUTO_CREATE);
}

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

    if(mBound) {
        unbindService(mConnection);

        mBound = false;
    }
}
double-beep
  • 5,031
  • 17
  • 33
  • 41
ferrazrafael
  • 83
  • 1
  • 10
  • Why dont you use intentservice instead? – youssefhassan Feb 11 '14 at 00:48
  • Isn't IntentService too simple for a Music Player? When the music is playing I need to interact with the MediaPlayer object, like changing the music or seekto in the music. Isn't IntentService just useful for simple long background running operations? – ferrazrafael Feb 11 '14 at 01:07
  • I'm trying to follow the example from this documentation http://developer.android.com/guide/components/bound-services.html – ferrazrafael Feb 11 '14 at 01:36

2 Answers2

1

You need to check on onStart() that is service running or not. If service is already running, then you need to just bind it. But in your current code you creating service everytime.

You should try to use Service.START_STICKY for checking that service is already running or not. You can see : Service , start Sticky or start not sticky

I think it will help you to update your service class.

Community
  • 1
  • 1
Shahinoor Shahin
  • 685
  • 3
  • 14
0

I could fix it add startService(...) to the OnStart( ) method. I didnt understand why this fixed, but seems that I need to do that. If anyone knows why please add. Thanks for everyone help.

this is how OnStart got:

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

    Intent service = new Intent(this,MyService.class);

    bindService(service, mConnection, Context.BIND_AUTO_CREATE);

    startService(service);
}
ferrazrafael
  • 83
  • 1
  • 10