androidandroid-serviceandroid-service-binding

How to keep service alive even after activity destroyed?


Here i am running a service for music play back. This code snippet is in my onStart() method of my Activity

if(musicServiceStartIntent == null) {
            musicServiceStartIntent = new Intent(this, MusicService.class);
            startService(musicServiceStartIntent);
            bindService(musicServiceStartIntent, musicConnection, Context.BIND_AUTO_CREATE);
        } 

First i'm starting my service then binding it. And i am calling unbindservice() in onDestroy() method. My Activity got destroyed and service stopped.

unbindService(musicConnection);

Manifest file declaration

<service android:name=".Services.MusicService"/>

How can i keep my service running in background even after activity destroyed. I refer few threads of StackOverflow but they are not helpful.


Solution

  • Use your service in startForeground, using Notification you can keep your service alive..