【问题标题】:Why can't we call StopForeground() method in the broadcast receiver class?为什么我们不能在广播接收器类中调用 StopForeground() 方法?
【发布时间】:2016-08-02 16:56:11
【问题描述】:

我有一个广播接收器类,当我收到特定广播时,我想停止前台通知。所以我尝试了context.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();

        }


    }
}

【问题讨论】:

    标签: android broadcastreceiver android-notifications foreground-service


    【解决方案1】:

    stopForeground()Service 类的一部分,因此不能从接收器或提供给它的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"))
    

    【讨论】:

    • 我们不能获取服务类的引用然后调用方法吗?
    • @WeirdNerd 是的,它是Service 类中的公共方法。所以,你只需要一个 Service 实例来调用它。
    • 广播接收器中如何获取服务引用对象?
    • @WeirdNerd 为什么不只从Service 实例中阻止它?您可以将与上述相同的接收器放入您的Service 中,然后在此处直接调用stopForeground()
    • 你的意思是在服务内部创建一个继承广播接收器的内部类?
    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-09
      • 2019-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-08
      • 1970-01-01
      相关资源
      最近更新 更多