为什么我们不能在广播接收器类中调用StopForeground()方法? [英] Why can't we call StopForeground() method in the broadcast receiver class?
问题描述
我有一个广播接收器类,当我接收到一个特定的广播时,我想停止前台通知.因此,我尝试了context.stopForeground()
,但智能感知未显示该方法.我们如何在广播接收器类中调用stopForeground()
方法?
I have a broadcast receiver class and when I receive a particular broadcast I would like to stop the foreground notification. So I tried context.stopForeground()
but the intellisense did not show the method. How can we call the stopForeground()
method in the broadcast receiver class ?
public class Broad extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction()==Const.ACTION_STOP)
{
// unable to call like this
context.stopForeground();
}
}
}
推荐答案
stopForeground()
是Service
类的一部分,因此不能从接收者或提供给它的context
调用它.
stopForeground()
is part of the Service
class and therefore it cannot be called from either the receiver or the context
provided to it.
要将现有的Service
中的BroadcastReceiver
设置为实例变量,请执行以下操作:
To setup a BroadcastReceiver
in your existing Service
as an instance variable:
private final BroadcastReceiver mYReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Bla bla bla
stopForeground(NOTIF_ID);
};
您可以使用以下方式仅在Service
(可能在onStartCommand()
上)上注册此接收器:
You register this receiver in your Service
only (possibly on onStartCommand()
), using:
IntentFilter iFilter = new IntentFilter("my.awesome.intent.filter");
registerReceiver(mYReceiver, iFilter);
这将使每次触发带有IntentFilter
的广播时都可以触发mYReceiver
,您可以在应用中的任何位置进行以下操作:
This will enable mYReceiver
to be triggered whenever a broadcast with that IntentFilter
is fired which you can do from anywhere in your app as:
sendBroadcast(new Intent("my.awesome.intent.filter"))
这篇关于为什么我们不能在广播接收器类中调用StopForeground()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!