Play music in the background of an Android application

I have a simple application in which there are several actions. I had to play background music while the user was using the application. I also want him to play all the time while the user is using the application, and not playing when the application is no longer in the foreground.

I read and tried a couple of things. I tried to launch MediaPlayer in the first action, which is similar to the options menu, but it either never stops or randomly stops in the next action. I tried to launch MediaPlayer in the first action, then when the button is pressed to start the next action, I save the current position time, pause MediaPlayer and pass the time for the next action, and then create a new MediaPlayer in the next activity and resume it. This method is fine, but if the user clicks the back button, everything starts with a circle, and he still plays when the application is not visible.

I also considered using onResume () and onPause (), but this is only useful for one action at a time. Do I need to create a service? I have never used the service before, and I don’t think it will stop the music when the application is not visible.

I just want to add to the background music app. I realized that it will be easier than that. Any help or ideas would be greatly appreciated. Also knowing if this is possible would be helpful.

+3
source share
1 answer

You need a service for this. You have to create a service and bind to the onResume activity and cancel it onStop, so when all the actions are not tied, ending the service is the best way to implement the music that caused the whole application

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

Source: https://habr.com/ru/post/1796719/


All Articles