How to start a service when a button is enabled and stop it when the button is disabled?

How to start a service when a button is enabled and stop it when the button is disabled?
0

#1

I am currently using this code, to start the service and stop it, but the service is never stopped. What is wrong?

final Switch enableSwitch = (Switch) findViewById(R.id.isEnabledSwitch);
    enableSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                startService(new Intent(getBaseContext(), la_svc.class));
            }
            else {
                stopService(new Intent(getBaseContext(), la_svc.class));
                stopService(new Intent(getBaseContext(), lb_svc.class));
            }
        }
    });

disableservice.java
What have I done wrong? How can I stop a service, when the switch is unchecked?


#2

Well add debugging prints if you don’t want to step through the code with a debugger.


#3

Nope. I want this at run time


#4

You’ve already screwed up if you can’t run a separate instance or a minimal reproducible test.