java - stopService 并停止获取消息
问题描述
我想停止我的服务并停止向我正在活动的 ma 处理程序获取数据。和服务我连接到 USB 并从这个端口获取数据。
我尝试这样做:
usbService.stopSelf();
Intent intent = new Intent(MainMenu.this, UsbService.class);
usbService.stopService(intent);
但我一直都有来自服务的数据。
我像这样开始我的服务:
private void startService(Class<?> service, ServiceConnection serviceConnection, Bundle extras) {
if (!UsbService.SERVICE_CONNECTED) {
Intent startService = new Intent(this, service);
if (extras != null && !extras.isEmpty()) {
Set<String> keys = extras.keySet();
for (String key : keys) {
String extra = extras.getString(key);
startService.putExtra(key, extra);
}
}
startService(startService);
}
Intent bindingIntent = new Intent(this, service);
bindService(bindingIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
解决方案
您需要首先通过调用 unBindService 取消绑定您的服务。正如您在服务文档中看到的:
请注意,如果已停止的服务仍然有绑定了 BIND_AUTO_CREATE 集的 ServiceConnection 对象,则在删除所有这些绑定之前,它不会被销毁。有关服务生命周期的更多详细信息,请参阅服务文档。
您需要在停止服务之前取消绑定绑定到服务的所有对象以销毁服务。
编辑:回答你的问题。添加一个布尔变量 mBound。覆盖这些方法。
public void onServiceConnected(ComponentName className, IBinder service) {
mBound = true;
}
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
在您的活动的 onStop 方法中,添加以下内容:
@Override
public void onStop()
{
super.onStop();
if (mBound) {
try {
unbindService(mConnection);
} catch (java.lang.IllegalArgumentException e)
{
//handle exception here
}
}
mBound = false;
}
推荐阅读
- reactjs - 具有生产反应构建的部署管道
- java - 如何解决 Java util 输入不匹配错误
- angular - 为什么 Typescript 要求分配 Getter?
- java - System.currentTimeMillis() 表现得很奇怪
- javascript - 如何将故事书嵌套的 storiesOf api 转换为 CSF 格式
- regex - 匹配除 Tcl 中的正则表达式模式之外的所有内容
- python - NLP-Name Entity Recognition:如何将实体的不同命名映射到同一个实体?AMC vs AMC 娱乐 vs AMC 剧院
- c# - 使用 PostAsync 将内容正文中的 JSON 传递到端点
- vue.js - ( Vue.js ) 为什么带有 $emit 的按钮不起作用?
- css - 在按钮上单击更改文本值