首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我们不能在广播接收器类中调用StopForeground()方法呢?

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

Stack Overflow用户
提问于 2016-08-03 00:56:11
回答 2查看 758关注 0票数 1

我有一个广播接收器类,当我接收到特定的广播时,我想停止前台通知。所以我尝试了context.stopForeground(),但是智能感知没有显示该方法。如何调用broadcast receiver类中的stopForeground()方法?

代码语言:javascript
复制
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();

        }


    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-08-03 00:59:27

stopForeground()Service类的一部分,因此既不能从接收器调用,也不能从提供给它的context调用。

要将现有Service中的BroadcastReceiver设置为实例变量,请执行以下操作:

代码语言:javascript
复制
    private final BroadcastReceiver mYReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // Bla bla bla
            stopForeground(NOTIF_ID);
    };

您只能在您的Service (可能是在onStartCommand()上)中注册此接收器,方法是:

代码语言:javascript
复制
IntentFilter iFilter = new IntentFilter("my.awesome.intent.filter");
registerReceiver(mYReceiver, iFilter);

这将使mYReceiver能够在使用该IntentFilter的广播被触发时触发,您可以在应用程序中的任何位置执行以下操作:

代码语言:javascript
复制
sendBroadcast(new Intent("my.awesome.intent.filter"))
票数 2
EN

Stack Overflow用户

发布于 2021-06-16 17:16:17

如果您想在您的接收器中停止广播接收器//

代码语言:javascript
复制
      @Override
        public void onReceive(Context context, Intent intent) {
       context.stopService(new Intent(context, YourService.class);
}

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38726398

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档