3

I have a simple application that has several activities in it. I was to play some background music while the user uses the app. I also want it to play the whole time while the user is using the app, and not play when the app is no longer in the foreground.

I have read and tried a couple of things. I've tried starting the MediaPlayer in the first activity, which is like an options menu, but it either never quits or stops randomly in the next activity. I've tried starting the MediaPlayer in the first activity, then when a button is pressed to start the next activity, I save the current position time, pause the MediaPlayer and pass the time to the next activity, then create a new MediaPlayer in the next activity and have it resume. This way is ok, but if the user hits the back button, things start to over lap and it still plays when the app is not visible.

I have also looked at using the onResume() and onPause(), but this is only good for one activity at a time. Do I need to create a service? I've never used a service before and I don't think that will stop the music when the app is not visible.

I just simply want to add some background music to my app. I figured that it would be easier than this. Any help or ideas would be greatly appreciated. Also knowing if this is even possible would be of some help.

sfrider0
  • 363
  • 1
  • 3
  • 6

1 Answers1

0

You need a service for that, You neeed to create a service and bind to the activity onResume and unbind it onStop, so when all the activities are unbinded the service ends is the best way to implement music trought the whole app

create a service and then do something like that

public ServiceConnection Scon = new ServiceConnection() {

    public void onServiceConnected(ComponentName name, IBinder binder)
    {
        mServ = ((DMusic.ServiceBinder) binder).getService();
    }

    public void onServiceDisconnected(ComponentName name)
    {
        mServ = null;
    }
};

public void doBindService()
{
    if (!mIsBound)
    {
        bindService(new Intent(this, DMusic.class), Scon, Context.BIND_AUTO_CREATE);
        mIsBound = true;
    }
}

public void doUnbindService()
{
    if (mIsBound)
    {
        unbindService(Scon);
        mIsBound = false;
    }
}


@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    doBindService();
}




@Override
public void onStop()
{
    super.onStop();
    doUnbindService();
}
D4rWiNS
  • 2,585
  • 5
  • 32
  • 54