博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
如何使用LocalBroadcastManager?
阅读量:2290 次
发布时间:2019-05-09

本文共 6268 字,大约阅读时间需要 20 分钟。

如和所述,如何使用/定位LocalBroadcastManager

我试图谷歌它,但没有可用的代码开始?

文件说如果我想在我的应用程序进程内部进行广播,我应该使用它,但我不知道在哪里寻找这个。

任何帮助/评论?

更新 :我知道如何使用广播,但不知道如何在我的项目中使用LocalBroadcastManager


#1楼

我宁愿全面回答。

  1. LocalbroadcastManager包含在 3.0及更高版本中,所以你必须使用支持库v4进行早期版本。 看说明

  2. 创建广播接收器:

    private  onNotice= new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // intent can contain anydata Log.d("sohail","onReceive called"); tv.setText("Broadcast received !"); } };
  3. 在onResume中注册您的接收器,例如:

    protected void onResume() { super.onResume(); IntentFilter iff= new IntentFilter(MyIntentService.ACTION); LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, iff); } //MyIntentService.ACTION is just a public static string defined in MyIntentService.
  4. onPause中的unRegister接收器:

    protected void onPause() { super.onPause(); LocalBroadcastManager.getInstance(this).unregisterReceiver(onNotice); }
  5. 现在,每当从应用程序的活动或服务发送localbroadcast时,onReceive on onNotice将被调用:)。

编辑:您可以在这里阅读完整的教程


#2楼

可以在开发人员找到实现LocalBroadcastManager的Activity和Service的示例。 我个人发现它非常有用。

编辑:此后该链接已从网站中删除,但数据如下: :


#3楼

我们也可以在这里使用与broadcastManger相同的接口我正在通过接口共享broadcastManager的testd代码。

首先做一个像这样的界面:

public interface MyInterface {     void GetName(String name);}

2 - 这是第一个需要实现的类

public class First implements MyInterface{    MyInterface interfc;        public static void main(String[] args) {      First f=new First();            Second s=new Second();      f.initIterface(s);      f.GetName("Paddy");  }  private void initIterface(MyInterface interfc){    this.interfc=interfc;  }  public void GetName(String name) {    System.out.println("first "+name);    interfc.GetName(name);    }}

3 - 这是实现相同接口的第二个类,其方法自动调用

public class Second implements MyInterface{   public void GetName(String name) {     System.out.println("Second"+name);   }}

所以通过这种方法我们可以使用与broadcastManager相同的接口。


#4楼

当你玩LocalBroadcastReceiver时我会建议你试试 - 你肯定会意识到它与LBR相比它的区别和用处。 可以使用更少的代码,可以自定义接收者的线程(UI / Bg),检查接收器可用性,粘性事件,事件作为数据传递等。


#5楼

在接收结束时:

  • 首先注册LocalBroadcast Receiver
  • 然后处理onReceive中的传入意图数据。

    @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this); lbm.registerReceiver(receiver, new IntentFilter("filter_string")); } public BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent != null) { String str = intent.getStringExtra("key"); // get all your data from intent and do what you want } } };

发送结束时:

Intent intent = new Intent("filter_string");   intent.putExtra("key", "My Data");   // put your all data using put extra    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

#6楼

如何将全局广播更改为LocalBroadcast

1)创建实例

LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);

2)用于注册BroadcastReceiver

更换

registerReceiver(new YourReceiver(),new IntentFilter("YourAction"));

localBroadcastManager.registerReceiver(new YourReceiver(),new IntentFilter("YourAction"));

3)用于发送广播消息

更换

sendBroadcast(intent);

localBroadcastManager.sendBroadcast(intent);

4)取消注册广播消息

更换

unregisterReceiver(mybroadcast);

localBroadcastManager.unregisterReceiver(mybroadcast);

#7楼

androidx.localbroadcastmanager 版中已被弃用

原因

LocalBroadcastManager是一个应用程序范围的事件总线,并在您的应用程序中包含图层违规; 任何组件都可以侦听来自任何其他组件的事件。 它继承了系统BroadcastManager不必要的用例限制; 开发人员必须使用Intent,即使对象只存在于一个进程中而且永远不会离开它。 出于同样的原因,它不遵循功能方面的BroadcastManager。

这些加起来令人困惑的开发人员体验。

替换

您可以将LocalBroadcastManager使用替换为可观察模式的其他实现。 根据您的使用情况,合适的选项可能是或反应流。

LiveData的优势

您可以使用单例模式扩展LiveData对象以包装系统服务,以便可以在应用程序中共享它们。 LiveData对象连接到系统服务一次,然后任何需要该资源的观察者都可以只观看LiveData对象。

public class MyFragment extends Fragment {    @Override    public void onActivityCreated(Bundle savedInstanceState) {        super.onActivityCreated(savedInstanceState);        LiveData
myPriceListener = ...; myPriceListener.observe(this, price -> { // Update the UI. }); }}

observe()方法将片段( LifecycleOwner一个实例)作为第一个参数传递。 这样做表示此观察者绑定到与所有者关联的Lifecycle对象,这意味着:

  • 如果Lifecycle对象未处于活动状态,则即使值发生更改,也不会调用观察者。

  • 销毁Lifecycle对象后,会自动删除观察者

LiveData对象具有生命周期感知这一事实意味着您可以在多个活动,片段和服务之间共享它们。


#8楼

以下是如何使用广播接收器示例


#9楼

无论如何我会回答这个问题。 以防有人需要它。

ReceiverActivity.java

监视名为"custom-event-name"的事件的通知的活动。

@Overridepublic void onCreate(Bundle savedInstanceState) {  ...  // Register to receive messages.  // We are registering an observer (mMessageReceiver) to receive Intents  // with actions named "custom-event-name".  LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,      new IntentFilter("custom-event-name"));}// Our handler for received Intents. This will be called whenever an Intent// with an action named "custom-event-name" is broadcasted.private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {  @Override  public void onReceive(Context context, Intent intent) {    // Get extra data included in the Intent    String message = intent.getStringExtra("message");    Log.d("receiver", "Got message: " + message);  }};@Overrideprotected void onDestroy() {  // Unregister since the activity is about to be closed.  LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);  super.onDestroy();}

SenderActivity.java

发送/广播通知的第二个活动。

@Overridepublic void onCreate(Bundle savedInstanceState) {  ...  // Every time a button is clicked, we want to broadcast a notification.  findViewById(R.id.button_send).setOnClickListener(new View.OnClickListener() {    @Override    public void onClick(View v) {      sendMessage();    }  });}// Send an Intent with an action named "custom-event-name". The Intent sent should // be received by the ReceiverActivity.private void sendMessage() {  Log.d("sender", "Broadcasting message");  Intent intent = new Intent("custom-event-name");  // You can also include some extra data.  intent.putExtra("message", "This is my message!");  LocalBroadcastManager.getInstance(this).sendBroadcast(intent);}

使用上面的代码,每次单击按钮R.id.button_send ,都会广播一个Intent, mMessageReceiver ReceiverActivitymMessageReceiver ReceiverActivity

调试输出应如下所示:

01-16 10:35:42.413: D/sender(356): Broadcasting message01-16 10:35:42.421: D/receiver(356): Got message: This is my message!

#10楼

在Eclipse中,最终我必须通过右键单击我的项目并选择以下内容来添加兼容性/支持库

Android工具 - > 添加支持库

一旦添加,我就可以在我的代码中使用LocalBroadcastManager类。


Android兼容性库

转载地址:http://bwcnb.baihongyu.com/

你可能感兴趣的文章
rviz的简单使用
查看>>
解决ROS的usb_cam节点无法正常读取mjpeg格式摄像头的方法
查看>>
Ubuntu VNC 如何调整分辨率
查看>>
病毒编程技术-3
查看>>
病毒编程技术-4
查看>>
病毒编程技术-5
查看>>
第9周上机实践项目1——利用循环求和
查看>>
第9周上机实践项目2——分数的累加
查看>>
第9周上机实践项目3——输出星号图
查看>>
第9周上机实践项目4——乘法口诀表
查看>>
第9周上机实践项目5——程序填充题
查看>>
第9周上机实践项目6——穷举法解决组合问题(1~3)
查看>>
第9周上机实践项目6——穷举法解决组合问题(3~7)
查看>>
第九周感想——就这样前进!
查看>>
第10周上机实践项目1——程序填充与阅读
查看>>
第10周上机实践项目2——M$pszi$y是嘛意思?
查看>>
第10周上机实践项目3——血型统计
查看>>
第10周上机实践项目5——输出完数
查看>>
hdu5793——A Boring Question(快速幂+逆元)
查看>>
poj1797——Heavy Transportation(最大生成树)
查看>>