停止服务作为前台运行的正确方法是什么 [英] What is the proper way to stop a service running as foreground
问题描述
我正在尝试停止作为前台服务运行的服务.
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.
这篇关于停止服务作为前台运行的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!