2

I have a problem with service.

In method onCreate I'm creating media player. When I'm moving between activities, I'm able to access service smoothly and it keeps the same media player instance. Although, when I leave application (audio from services mediaplayer is still playing) and then I return to application - I get new MediaPlayer instance. Audio stream from previous instance is still playing.

I would like to have the access to the same instance of MediaPlayer as preiously to manipulate playing song (pause for example).

Do you know what may be the issue?

class PlayerService : Service(), MediaPlayer.OnPreparedListener, PlayerServiceContract.ServiceContract {

    private val mBinder = PlayerBinder()

    private var mPlayer: MediaPlayer? = null

    private var mPresenter: PlayerServiceContract.Presenter? = null

    private var mRecording: Recording? = null

    override fun onCreate() {
        super.onCreate()
        mPlayer = MediaPlayer()
        mPlayer?.setWakeMode(applicationContext,
                PowerManager.PARTIAL_WAKE_LOCK)
        mPlayer?.setAudioStreamType(AudioManager.STREAM_MUSIC)        
        mPlayer?.setOnPreparedListener(this)
Pavya
  • 6,015
  • 4
  • 29
  • 42
Orbite
  • 505
  • 4
  • 8

1 Answers1

1

A bound service will be shut down if the service gets unbound for all of its bindings.
A service that is started by startService() will be shut down if the service is shut down by calling stopSelf() or stopService().

A service that is both called by startService() and bindService() will be destroyed if AND stopSelf() or stopService().

A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is started or there are one or more connections to it with the Context.BIND_AUTO_CREATE flag. Once neither of these situations hold, the service's onDestroy() method is called and the service is effectively terminated. All cleanup (stopping threads, unregistering receivers) should be complete upon returning from onDestroy().
- From Service.Service Lifecycle | Android Developers Doc

In your case, when the activities are gone, the service seems to enter the unbound state and may be destroyed.
Maybe you have to call startService() in the same service when you start the play, and call stopSelf() when you stop the play, so that the service cannot be destroyed while it is playing media.

NOTE: Some say that you have to call stopSelf() after unbinding all. Some say that the order of stop and unbind is not relevant. I don't know which is correct.

Naetmul
  • 14,544
  • 8
  • 57
  • 81
  • Thank you, I actually did not start service by startService but bindService, and this was the root of the problem. – Orbite May 19 '17 at 15:25