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

ぐ巨炮叔叔 提交于 2019-12-12 02:09:21

问题


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();

        }


    }
}

回答1:


stopForeground() is part of the Service class and therefore it cannot be called from either the receiver or the context provided to it.

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);
    };

You register this receiver in your Service only (possibly on onStartCommand()), using:

IntentFilter iFilter = new IntentFilter("my.awesome.intent.filter");
registerReceiver(mYReceiver, iFilter);

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


来源:https://stackoverflow.com/questions/38726398/why-cant-we-call-stopforeground-method-in-the-broadcast-receiver-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!