如何从活动中停止START_STICKY安卓服务

3

我创建了一个Android服务,希望它一直运行,直到从活动中请求关闭。我使用START_STICKY返回onStartCommand()创建了它,这样即使我关闭应用程序,它也可以正常运行。但是问题在于,我想通过按钮点击(例如单选框:在后台运行 是/否)停止服务。

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");
    }
}
1个回答

2
在您的按钮的 onClick() 方法中,执行以下操作:
Intent intent = new Intent(MyActivity.this, MyService.class);
stopService(intent);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接