zoukankan      html  css  js  c++  java
  • LocalBroadcastManager 使用小解

    最近在开发平板项目,完全是fragmentactivity+fragment的结构。看起来似乎简单,但是和以前不同的是,业务逻辑非常复杂,多处的非常规跳转,
    fragment之间的数据交换,一处更新多处更新等操作,有时玩起来都心塞。项目背景介绍完毕。
    现在有这样一个场景,项目需求是,后台可配置功能,也就是说app端所有的功能都是后台配置上去的动态生成,对应的功能界面如下图。

    左边是功能索引,根据后台配置动态生成,右边每个功能对应的界面。已经实现的是左边使用fragment,右边也是fragment,
    点击不同的功能号切换到不同的功能界面。现在在1.1fragment中,有一个按钮点击需要实现

    1)跳转到功能号为2的功能界面,

    2)同时左边的功能号对应的也需要切换过来。
    需求1)通过回调可以实现,而需求2)简单点实现是通过发从程序内广播实现。

    下面主要介绍下程序内广播。 1.LocalBroadcastManager基本介绍 这个类是在v4包中的,谷歌官方的介绍是: Helper to register for and send broadcasts of Intents to local objects within your process. This is has a number of advantages over sending global broadcasts with sendBroadcast(Intent):

     You know that the data you are broadcasting won't leave your app, so don't need to worry about leaking private data.  It is not possible for other applications to send these broadcasts to your app, so you don't need to worry about having security holes they can exploit.  It is more efficient than sending a global broadcast through the system. 

    本人献丑翻译下:
     能够完成在应用内的广播发送,而且比全局广播更具优势:
     1).广播只会在你的应用内发送,所以无需担心数据泄露,更加安全。
     2).其他应用无法发广播给你的应用,所以也不用担心你的应用有别人可以利用的安全漏洞
     3).相比较全局广播,它不需要发送给整个系统,所以更加高效。

    2. 使用方式
    广播注册:

    1 LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(getActivity());
    2 IntentFilter filter = new IntentFilter();
    3 filter.addAction(ACTION);
    4 myBroadcastReciver = new MyBroadcastReciver();
    5 localBroadcastManager.registerReceiver(myBroadcastReciver, filter);

    广播发送

    1 Intent intent = new Intent();
    2 intent.setAction(SaleLeftFragment.ACTION);
    3 intent.putExtra(TAG, data);
    4 LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);

    3.使用注意

    在使用的时候,请关注以下几点:

    1).LocalBroadcastManager注册广播只能通过代码注册的方式。

    2).LocalBroadcastManager注册广播后,一定要记得取消监听。

    3).重点的重点,使用LocalBroadcastManager注册的广播,您在发送广播的时候务必使用LocalBroadcastManager.sendBroadcast(intent);否则您接收不到广播,不要怪政府哈。

    谢谢。上面的需求实现也欢迎各位童鞋多给意见和建议。

  • 相关阅读:
    恢复oracle中误删除drop掉的表
    mysql安装教程(小白入门)
    各版本mysql下载安装教程(超详细,超全)
    Jetbrains系列产品2019.3.3及以下版本最新激活方法
    老友记全季高清视频(中英字幕)及学习资料(剧本,音频,台词)等等!
    电脑桌面快捷方式小箭头的去与留!
    Sublime Text 3破解教程及应用技巧和诀窍(完美激活)
    7个堪称经典的电脑小技巧,让你办公事半功倍!
    怎么优化,美化电脑桌面(Fences v3.0.9 中文破解版)来这里教你。
    JAVA
  • 原文地址:https://www.cnblogs.com/xilinch/p/4238122.html
Copyright © 2011-2022 走看看