How to stop Service from another activity in Android?

Tramway11 picture Tramway11 · Jul 16, 2013 · Viewed 10.1k times · Source

I have 2 activities, A & B. The Service starts in B with such code:

 startService(new Intent(this, PlayerService.class));
             Intent connectionIntent = new Intent(this, PlayerService.class);
             bindService(connectionIntent, mp3PlayerServiceConnection, Context.BIND_AUTO_CREATE);

 private ServiceConnection mp3PlayerServiceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName arg0, IBinder binder) {
        mp3Service = ((LocalBinder) binder).getService();
        Thread t = new Thread() {
        public void run() {
        mp3Service.playSong(getApplicationContext(),url);
        }
        };
        t.start();
    }
    @Override
    public void onServiceDisconnected(ComponentName arg0) {
     }
 };

I need to have a possibility to close the service when I'm on activity A (B is closed, but music plays). How to call StopService from A onDestroy()? Need I to unbind it, if yes, how and where?

Simply putting stopService(new Intent(this,PlayerService.class)); leads to an error: Activity B has leaked Service connection ... that was originally bound here. (But B is already closed)

Answer

Hoan Nguyen picture Hoan Nguyen · Jul 16, 2013

You should unbind service in B onStop(), then you can call stopService in A.