如何使用LocalBroadcastManager?

google docsService broadcast doc中所述,如何使用/定位LocalBroadcastManager

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

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

任何帮助/评论?

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


#1楼

我宁愿全面回答。

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

  2. 创建广播接收器:

     private BroadcastReceiver 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将被调用:)。

编辑:您可以在这里阅读完整的教程LocalBroadcastManager:Intra应用程序消息传递


#2楼

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

编辑:此后该链接已从网站中删除,但数据如下: https//github.com/carrot-garden/android_maven-android-plugin-samples/blob/master/support4demos/src/com/例如/机器人/ supportv4 /内容/ LocalServiceBroadcaster.java


#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时我会建议你试试Green Robot的EventBus - 你肯定会意识到它与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 1.1.0 版中已被弃用

原因

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

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

替换

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

LiveData的优势

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

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

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

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

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

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


#8楼

以下是如何使用广播接收器https://youtu.be/m_aP8E35jaE的示例


#9楼

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

ReceiverActivity.java

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

@Override
public 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);
  }
};

@Override
protected void onDestroy() {
  // Unregister since the activity is about to be closed.
  LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
  super.onDestroy();
}

SenderActivity.java

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

@Override
public 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 message
01-16 10:35:42.421: D/receiver(356): Got message: This is my message! 

#10楼

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

Android工具 - > 添加支持库

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


Android兼容性库

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值