简体   繁体   中英

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.

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.

Well, as far as I know Servive belongs **to the thread, where it has been created **.

So if you would like to keep the service running, after the Activity closed, you have to start it from a different place. I would recommend an Application subclass OR you can do it from an Activity with: new Thread(){...startServiceHere...}.start();

Thread t = new Thread(){
public void run(){
getApplicationContext().bindService(
    new Intent(getApplicationContext(), MyAndroidUpnpServiceImpl.class),
    serviceConnection,
    Context.BIND_AUTO_CREATE
);}
};
t.start();

//service code copied from @Samuh

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM