为什么我们不能在广播接收器 class 中调用 StopForeground() 方法?

Why can't we call StopForeground() method in the broadcast receiver class?

我有一个广播接收器class,当我收到一个特定的广播时,我想停止前台通知。所以我尝试了 context.stopForeground() 但智能感知没有显示该方法。我们如何在广播接收器 class 中调用 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 class 的一部分,因此它不能从接收器或提供给它的 context 调用。

要在现有 Service 中设置一个 BroadcastReceiver 作为实例变量:

    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"))

如果你想从广播接收器中停止它 //在你的接收器中

      @Override
        public void onReceive(Context context, Intent intent) {
       context.stopService(new Intent(context, YourService.class);
}

同时在相关服务的onDestroy方法中添加stopForground(true)