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

编程入门 行业动态 更新时间:2024-10-20 16:47:11
本文介绍了停止服务作为前台运行的正确方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I am trying to stop a service which is running as foreground service.

当前问题是,当我致电stopService()时,通知仍然存在.

The current issue is that when I call stopService() the notification still stays.

因此,在我的解决方案中,我添加了一个要注册到onCreate()

So in my solution I have added a receiver which I am registering to inside the onCreate()

在onReceive()方法内部,我调用stopforeground(true),它隐藏了通知. 然后stopself()停止服务.

Inside the onReceive() method I call stopforeground(true) and it hides the notification. And then stopself() to stop the service.

在onDestroy()内部,我未注册接收器.

Inside the onDestroy() I unregistered the receiver.

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

Is there a more proper way to handle this? because stopService() simply doesn't work.

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

推荐答案

从您的活动调用startService(intent)并将其传递给一些数据,这些数据将表示停止服务的关键.

From your activity call startService(intent) and pass it some data that will represent a key to stop the service.

从服务呼叫stopForeground(true),然后在其后呼叫stopSelf().

From your service call stopForeground(true) and then stopSelf() right after it.

更多推荐

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

本文发布于:2023-11-26 00:26:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631928.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:前台   正确   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!