Search code examples
androidandroid-activityservicedestroy

Stop service and close app


My app use a background music service. I have a button to quit my app but I can't find anything to close my app and my service. I bind my service to my activity.

I tried:

unbindService(serviceConnection);
myService().stopSelf();
stopService(new Intent(this, MediaPlayer.class));

and absolutely nothing works !!! The service continues.

How can I do to destroy my service and how can I do to close my app ??

Tx

EDIT:

I use this in the onCreate method

Intent intent = new Intent(this, serviceClass);
bindService(intent, serviceConnection, BIND_AUTO_CREATE);

And in the MediaPlayer class

public class LocalBinder extends Binder {
        public MediaPlayer getService() {
            return MediaPlayer.this;
        }
    }
public IBinder onBind(Intent intent) {
    Log.i(TAG, "service bound");
    init();
    return mBinder;
}

And that... But I dont know if I really need to start the service. Bind the service already starts it

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_NOT_STICKY;
}

Now I did this

@Override
public void onDestroy() {
    player.stop();
    super.onDestroy();
}

The onDestroy method works only if i unbind the service ! This doesnt work at all:

        getService().stopSelf();
       this.stopService(new Intent(this, MediaPlayer.class));

So, how can I stop the service and how can I close the app ?


Solution

  • This is what I do in my app. onDestroy() method from the activity will be called when you close your app.

    private ServiceConnection musicServiceConnection = new ServiceConnection() {
    
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            MusicService.LocalBinder binder = (MusicService.LocalBinder) service;
            musicService = binder.getService();
            musicService.setCallbacks(MainActivity.this);
            musicServiceBound = true;
        }
    
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i(TAG, "MusicService service disconnected (unbinded)");
            musicServiceBound = false;
        }
    };
    
    
    @Override
    protected void onStart() {
        super.onStart();
        Intent intent1 = new Intent(this, MusicService.class);
        bindService(intent1, musicServiceConnection, Context.BIND_AUTO_CREATE);
    }
    
    
    @Override
    protected void onDestroy() {
        super.onDestroy()
        if(musicServiceBound){
            musicService.stopSelf();
            unbindService(musicServiceConnection);
        }
    }
    

    You wrote myService(), where you are creating another service using (). For closing your app programmatically you can refer to this question.