Android 如何使用LocalBroadcastManager?

Android 如何使用LocalBroadcastManager?,android,broadcastreceiver,Android,Broadcastreceiver,如何使用/定位和中所述的LocalBroadcastManager 我试着用谷歌搜索它,但一开始没有可用的代码 文件说,如果我想在我的应用程序的进程中进行内部广播,我应该使用它,但我不知道在哪里可以找到它 有什么帮助/意见吗 更新:我知道如何使用广播,但不知道如何在我的项目中获得可用的LocalBroadcastManager。无论如何,我会回答这个问题。以防有人需要 ReceiverActivity.java 监视名为“自定义事件名称”的事件通知的活动 SenderActivity.java

如何使用/定位和中所述的
LocalBroadcastManager

我试着用谷歌搜索它,但一开始没有可用的代码

文件说,如果我想在我的应用程序的进程中进行内部广播,我应该使用它,但我不知道在哪里可以找到它

有什么帮助/意见吗


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

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

ReceiverActivity.java 监视名为
“自定义事件名称”
的事件通知的活动

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
,就会广播一个意图,并由
ReceiverActivity
中的
mMessageReceiver
接收

调试输出应如下所示:

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! 

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

Android工具->添加支持库


添加后,我就可以在代码中使用
LocalBroadcastManager



我想全面地回答

  • android 3.0及以上版本中包含LocalbroadcastManager,因此 将支持库v4用于早期版本。参见说明

  • 创建广播接收器:

    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 !");
    
        }
    };
    
  • 在活动的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.
    
  • 在onPause中注销接收器:

    protected void onPause() {
      super.onPause();
      LocalBroadcastManager.getInstance(this).unregisterReceiver(onNotice);
    }
    
  • 现在,无论何时从应用程序的活动或 服务,onReceive或onNotice将被调用:)


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

    可以在开发人员中找到实现LocalBroadcastManager的活动和服务的示例。我个人觉得它非常有用

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

    我们也可以使用与broadcastManager相同的界面。在这里,我将通过界面共享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功能相同的界面。

    当您充分使用LocalBroadcastReceiver时,我建议您尝试一下-您一定会意识到它与LBR的区别和用处。代码更少,可自定义接收器线程(UI/Bg),检查接收器可用性,粘性事件,事件可用作数据传递等。

    接收端:

    • 第一寄存器本地广播接收机
    • 然后在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);
    
    如何将全局广播更改为本地广播 1) 创建实例 2) 用于注册广播接收机 替换

    3) 用于发送广播消息 替换

    4) 用于注销广播消息 替换

    localbroadcastmanager已弃用,请改用observable模式的实现。
    androidx.localbroadcastmanager
    版本中不推荐使用

    原因


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

    这些增加了一种令人困惑的开发人员体验

    更换


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

    LiveData的优势

    您可以使用singleton模式扩展
    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.
            });
        }
    }
    
    公共类MyFragment扩展了片段{
    @凌驾
    已创建ActivityState上的公共无效(Bundle savedInstanceState){
    super.onActivityCreated(savedInstanceState);
    LiveData myPriceListener=。。。;
    myPriceListener.观察(这个,价格->{
    //更新用户界面。
    });
    }
    }
    
    observe()
    方法将片段作为第一个参数传递,该片段是
    LifecycleOwner
    的实例。这样做表示此观察者绑定到与所有者关联的
    生命周期
    对象,这意味着:

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

    • 销毁生命周期对象后,观察者将 自动删除


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

    方法是在您的AndroidManifest.xml文件中用标记(也称为static)声明一个对象

    enter code here if (createSuccses){
                            val userDataChange=Intent(BRODCAST_USER_DATA_CHANGE)
                            LocalBroadcastManager.getInstance(this).sendBroadcast(
                                userDataChange
                            )
                            enableSpinner(false)
                            finish()
    
    发送广播有三种方式:
    sendOrderedBroadcast方法确保一次只向一个接收器发送广播。每个广播可以依次将数据传递给它后面的广播,或停止广播传播到接收它的接收器
    registerReceiver(new YourReceiver(),new IntentFilter("YourAction"));
    
    localBroadcastManager.registerReceiver(new YourReceiver(),new IntentFilter("YourAction"));
    
    sendBroadcast(intent);
    
    localBroadcastManager.sendBroadcast(intent);
    
    unregisterReceiver(mybroadcast);
    
    localBroadcastManager.unregisterReceiver(mybroadcast);
    
     public class MyFragment extends Fragment {
        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            LiveData<BigDecimal> myPriceListener = ...;
            myPriceListener.observe(this, price -> {
                // Update the UI.
            });
        }
    }
    
    enter code here if (createSuccses){
                            val userDataChange=Intent(BRODCAST_USER_DATA_CHANGE)
                            LocalBroadcastManager.getInstance(this).sendBroadcast(
                                userDataChange
                            )
                            enableSpinner(false)
                            finish()
    
    <receiver android:name=".YourBrodcastReceiverClass"  android:exported="true">
    <intent-filter>
        <!-- The actions you wish to listen to, below is an example -->
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
    </intent-filter>
    
    public abstract Intent registerReceiver (BroadcastReceiver receiver, 
                IntentFilter filter);
    
    public void onReceive(Context context, Intent intent) {
    //Implement your logic here
    }
    
    class MainActivity : AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            // register broadcast manager
            val localBroadcastManager = LocalBroadcastManager.getInstance(this)
            localBroadcastManager.registerReceiver(receiver, IntentFilter("your_action"))
        }
    
        // broadcast receiver
        var receiver: BroadcastReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                if (intent != null) {
                    val str = intent.getStringExtra("key")
                    
                }
            }
        }
    
        /**
         * Send broadcast method
         */
        fun sendBroadcast() {
            val intent = Intent("your_action")
            intent.putExtra("key", "Your data")
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
        }
    
        override fun onDestroy() {
            // Unregister broadcast
            LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver)
            super.onDestroy()
        }
    
    }
    
    object NotificationCenter {
        var observers: MutableMap<String, MutableList<NotificationObserver>> = mutableMapOf()
    
        fun addObserver(observer: NotificationObserver, notificationName: NotificationName) {
            var os = observers[notificationName.value]
            if (os == null) {
                os = mutableListOf<NotificationObserver>()
                observers[notificationName.value] = os
            }
            os.add(observer)
        }
    
        fun removeObserver(observer: NotificationObserver, notificationName: NotificationName) {
            val os = observers[notificationName.value]
            if (os != null) {
                os.remove(observer)
            }
        }
    
        fun removeObserver(observer:NotificationObserver) {
            observers.forEach { name, mutableList ->
                if (mutableList.contains(observer)) {
                    mutableList.remove(observer)
                }
            }
        }
    
        fun postNotification(notificationName: NotificationName, obj: Any?) {
            val os = observers[notificationName.value]
            if (os != null) {
                os.forEach {observer ->
                    observer.onNotification(notificationName,obj)
                }
            }
        }
    }
    
    interface NotificationObserver {
        fun onNotification(name: NotificationName,obj:Any?)
    }
    
    enum class NotificationName(val value: String) {
        onPlayerStatReceived("on player stat received"),
        ...
    }
    
    class MainActivity : AppCompatActivity(), NotificationObserver {
        override fun onCreate(savedInstanceState: Bundle?) {
            ...
            NotificationCenter.addObserver(this,NotificationName.onPlayerStatReceived)
        }
        override fun onDestroy() {
            ...
            super.onDestroy()
            NotificationCenter.removeObserver(this)
        }
    
        ...
        override fun onNotification(name: NotificationName, obj: Any?) {
            when (name) {
                NotificationName.onPlayerStatReceived -> {
                    Log.d(tag, "onPlayerStatReceived")
                }
                else -> Log.e(tag, "Notification not handled")
            }
        }
    
    NotificationCenter.postNotification(NotificationName.onPlayerStatReceived,null)