加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Android 发送广播简易工具类

发布时间:2020-05-28 21:18:22 所属栏目:Java 来源:互联网
导读:Android 发送广播简易工具类

下面是脚本之家 jb51.cc 通过网络收集整理的代码片段。

脚本之家小编现在分享给大家,也给大家做个参考。

    /** 
     * 发送广播简易工具类 
     * Created by Liam on 2015/4/2. 
     */  
    public class BroadcastUtil {  
      
        /** 
         * 构造函数设为private,防止外部实例化 
         */  
        private void BroadcastManager() {  
        }  
      
        /** 
         * 注册广播接收器 
         * 
         * @param ctx       Context(不可空) 
         * @param iReceiver IReceiver(不可空) 
         * @param action    Intent.Action(不可空) 
         */  
        public static void registerReceiver(Context ctx,final IReceiver iReceiver,final String action) {  
            if (ctx == null || iReceiver == null || action == null) throw new IllegalArgumentException("使用registerReceiver()注册广播时,参数Context、IReceiver和Action不能为空!");  
      
            BroadcastReceiver receiver = new BroadcastReceiver() {  
                @Override  
                public void onReceive(Context context,Intent intent) {  
                    iReceiver.onReceive(context,intent);  
                }  
            };  
            IntentFilter filter = new IntentFilter(action);  
            ctx.registerReceiver(receiver,filter);  
        }  
      
        /** 
         * 发送广播 
         * 
         * @param ctx    Context(不可空) 
         * @param i      Intent(可为null),不需要设置Action,请把Action作为参数传入 
         * @param action Intent.Action(不可空) 
         */  
        public static void send(Context ctx,Intent i,final String action) {  
            if (ctx == null || action == null) throw new IllegalArgumentException("使用send()发送广播时,参数Context和Action不能为空!");  
      
            if (i == null) i = new Intent();  
            i.setAction(action);  
            ctx.sendBroadcast(i);  
        }  
      
      
        /** 
         * 接收广播的页面需要实现,把接收后的操作覆写在OnReceive()方法里 
         */  
        public interface IReceiver {  
            void onReceive(Context ctx,Intent intent);  
        }  
      
    }  

以上是脚本之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。

如果觉得脚本之家网站内容还不错,欢迎将脚本之家网站推荐给程序员好友。

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读