Android 广播的使用

先创建一个类继承广播,并且定义一个接口传递所需要的参数

public class ADReceiver extends BroadcastReceiver {

    private BRInteraction brInteraction;
    @Override
    public void onReceive(Context context, Intent intent) {
        // 广告发送消息后,这里接受广播(ADSendMsg为发送广播标识)
        if (intent.getAction().equals("ADSendMsg")) {
            String name = intent.getExtras().getString("name");
            brInteraction.app2IsClosedcallBack(name);
        }
    }

    // 自定义接口实现对广告发送消息的处理
    public interface BRInteraction {
        public void app2IsClosedcallBack(String content);
    }

    public void setBRInteractionListener(BRInteraction brInteraction) {
        this.brInteraction = brInteraction;
      }
}

在需要接受广播的类里面注册广播

Tip:这个方法的类里面需要继承广播的接口

private void initBroadcastReciver() {
        IntentFilter mIntentFilter = new IntentFilter();
        mIntentFilter .addAction("ADSendMsg");
        myReceiver = new ADReceiver();
        // 注册此监听
        myReceiver.setBRInteractionListener(this);
        registerReceiver(myReceiver, mIntentFilter);
    }

在需要发送广播的地方

// 发送广播
private void sendBroadcastReciver() {
    Intent intent = new Intent("ADSendMsg");
    intent.putExtra("key", value);
    sendBroadcast(intent);
  }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,073评论 19 139
  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 14,022评论 6 13
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 176,094评论 25 709
  • 为你说 你是我心中一个白发苍苍的梦想 你是我陆里海里漂洋的港 你是细语万千 你是骄阳艳艳 你是我人山人海中的一睁眼...
    夏三三阅读 1,621评论 0 2
  • 仿佛昨天好像就是报道的那天 时间太快 转眼了两年 被分到了最严的那个班级 变态的老师 滑稽的我们 刚上的初一的新鲜...
    6大人阅读 1,153评论 0 0

友情链接更多精彩内容