Search code examples
androidservicemedia-playerintentservice

IntentService stop after activity stops


I have a simple activity which binds a connection to a IntnetService. The service just plays a MediaPlayer. I have implemented onDestroy inside the service. However after pressing back in main activity, I was expecting the service to run as usual as IntentService supposes to run in background in separated thread, but after debugging I realized that onDestory activity calls in IntentService class and destroys the Media Player in it. Where I am wrong probably?

This is my Activity

public class MainActivity extends AppCompatActivity{

    private void startAudio() {
        Intent intent = new Intent(Intent.ACTION_SYNC, null, this, PlayerService.class);
        bound = bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);

    }
}

This is my Service:

public class PlayerService extends IntentService{
    @Override
    public void onDestroy() {
        mediaPlayer.pause();
        mediaPlayer.reset();
        mediaPlayer.release();
    }
}

Solution

  • bindService is used to bind to service and service stops itself when it has no clients/connections left.Here,as activity is destroyed,service is also getting destroyed

    IntentService is supposed to run in background in separated thread until and unless it has work.But here,it is not getting work and hence getting destroyed.