android - 如何停止以自定义意图启动的 Android 服务
问题描述
我在 Android Studio 中构建了一个名为 MService 扩展服务的类,我像这样启动服务:-在与按钮关联的 onClick 内部-
Intent serviceIntent = new Intent(getApplicationContext(), MService.class);
serviceIntent.putExtra("ID", "1");
startService(serviceIntent);
服务onStartCommand
方法午餐并且工作得很好..
问题是单击按钮时我不知道如何结束服务,我尝试这样做:
stopService(new Intent(getApplicationContext(), MService.class));
在 onClick 方法中, onDestroy
午餐,但服务仍在运行我该如何停止它?
解决方案
在 onClick 方法中,onDestroy 午餐,但服务仍在运行
如果onDestroy()
您的服务被调用,那么之后,该服务没有运行。您的代码可能仍在运行。
如果您在服务中启动事物,例如后台线程,则通常在您的方法中停止并清理它们是您的工作。onDestroy()
推荐阅读
- android - 您的应用程序必须具有有效的 targetSdkVersion 集
- orientdb - OrientDB - 限制时间或防止执行大量查询
- chatbase - Chatbase 是否支持其他语言(葡萄牙语)?
- c++ - 添加自定义类型格式,以及所有常用选项
- javascript - 是否有导出与命名和默认导出相同的 const 的用例?
- mysql - 我有一个关于更新查询和数据库索引的示例问题
- python - 为什么 Python 3.6 中的字符串索引比 NumPy 索引慢 10 倍?
- c++ - 当我平均整数时丢失了多少信息?
- ruby-on-rails - 如何在rails中运行和提取mysql查询数据
- javascript - ExpressJS 下面是什么?