为什么我们不能在广播接收器类中调用StopForeground()方法? [英] Why can't we call StopForeground() method in the broadcast receiver class?

查看:230
本文介绍了为什么我们不能在广播接收器类中调用StopForeground()方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个广播接收器类,当我接收到一个特定的广播时,我想停止前台通知.因此,我尝试了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆