如何从 activity 停止 START_STICKY android 服务

How to stop START_STICKY android service from activity

我创建了一个 android 服务,我想保留 运行 直到我要求它从 activity 关闭。我用 START_STICKY return onStartcommand() 创建了它,即使我关闭应用程序也能正常工作并保持 运行 。但问题是我想在单击按钮时停止服务(例如单选按钮:运行 在后台 Yes/No)。

public class MyService extends Service {
    public MyService() {
    }

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

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

在按钮的 onClick() 方法中,执行以下操作:

Intent intent = new Intent(MyActivity.this, MyService.class);
stopService(intent);