首页 > 解决方案 > 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);
}

标签: javaandroidandroid-service

解决方案


您需要首先通过调用 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;
}

推荐阅读