Search code examples
androidbindingandroid-serviceandroid-music-player

Running Bindservice after the activity is destroyed


I'm kinda creating a music player with binder type service.I know if I use binder I should use stopSelf in activity but is there any way that I can run the service on activity destroy.I have a seekbar in my activity.if I use startService in OnDestroy I'm getting error in service.

MainActivity

private ServiceConnection music=new ServiceConnection(){

    @Override
    public void onServiceConnected(ComponentName p1, IBinder p2)
    {
        // TODO: Implement this method
        MusicBinder binder=(MusicBinder)p2;
        registerReceiver(broadcastReciever, new IntentFilter(MusicService.BROADCAST_ACTION));
        musicSrv = binder.getService();
        musicSrv.setList(songList);
        musicBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName p1)
    {
        // TODO: Implement this method
        if (mBroadCastIsRegistered)
        {
            try
            {
                unregisterReceiver(broadcastReciever);
                mBroadCastIsRegistered = false;}
            catch (Exception e)
            {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), e.getClass().getName() + "" + e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }
        musicBound = false;
    }
};

Manifest

<service
  android:name=".Musicservice"/>

I'm starting the service with thread.


Solution

  • You can startService then bindService from activity. That way when activity can unbind when it's done but music service will keep playing until stop self is called. So use both mechanisms are required to stop.