停止作为前台运行的服务的正确方法是什么

新手上路,请多包涵

我正在尝试停止作为前台服务运行的服务。

当前的问题是,当我调用 stopService() 时,通知仍然存在。

所以在我的解决方案中,我添加了一个接收器,我正在注册到 onCreate()

onReceive() 方法中,我调用了 stopforeground(true) 并隐藏了通知。然后 stopself() 停止服务。

onDestroy() 中,我注销了接收器。

有没有更合适的方法来处理这个问题?因为 stopService() 根本不起作用。

 @Override
public void onDestroy(){
  unregisterReceiver(receiver);
  super.onDestroy();
}

原文由 user1940676 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答
  1. 在您的活动中,调用 startService(intent) 并向其传递一些代表 停止服务 的密钥的数据。
  2. 从您的服务中,调用 stopForeground(true)
  3. 然后 stopSelf() 就在它之后。

原文由 Ilya Gazman 发布,翻译遵循 CC BY-SA 4.0 许可协议

从活动使用启动和停止前台服务:

 //start
    Intent startIntent = new Intent(MainActivity.this, ForegroundService.class);
    startIntent.setAction(Constants.ACTION.STARTFOREGROUND_ACTION);
    startService(startIntent);
//stop
    Intent stopIntent = new Intent(MainActivity.this, ForegroundService.class);
    stopIntent.setAction(Constants.ACTION.STOPFOREGROUND_ACTION);
    startService(stopIntent);

在您的前台服务中 - 使用(至少)此代码:

 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
        Log.i(LOG_TAG, "Received Start Foreground Intent ");
        // your start service code
    }
    else if (intent.getAction().equals( Constants.ACTION.STOPFOREGROUND_ACTION)) {
        Log.i(LOG_TAG, "Received Stop Foreground Intent");
    //your end servce code
        stopForeground(true);
        stopSelfResult(startId);
    }
    return START_STICKY;
}

原文由 Elad 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题