为什么我们不能在广播接收器类中调用StopForeground()方法?
问题描述:
我有一个广播接收器类,当我收到一个特定的广播时,我想停止前台通知。所以我尝试context.stopForeground()
,但智能感知没有显示该方法。我们如何在广播接收机类中调用stopForeground()
方法?为什么我们不能在广播接收器类中调用StopForeground()方法?
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
被调用。
要设置BroadcastReceiver
现有Service
作为一个实例变量:
private final BroadcastReceiver mYReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Bla bla bla
stopForeground(NOTIF_ID);
};
你在你的Service
只注册(可能在onStartCommand()
)这个接收器,使用:
IntentFilter iFilter = new IntentFilter("my.awesome.intent.filter");
registerReceiver(mYReceiver, iFilter);
这将使mYReceiver
每当与广告IntentFilter
被激发,你可以在你的应用程序的任何地方做:
sendBroadcast(new Intent("my.awesome.intent.filter"))
我们不能得到对服务类的引用,然后调用该方法吗? –
@WeirdNerd是的,它是'Service'类中的一个公共方法。所以,你只需要一个'Service'实例来调用它。 – Shaishav
如何在广播接收器中获得服务引用对象? –