如何使用/定位在谷歌文档和服务广播文档中描述的LocalBroadcastManager ?

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

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

任何帮助/评论?

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


当前回答

使用LocalBroadcastManager的Kotlin版本:

请检查下面的注册代码, 发送和接收广播消息。

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()
    }

}

其他回答

我是一名iOS开发者,所以我做了一个类似于NotificationCenter的解决方案:

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)
enter code here if (createSuccses){
                        val userDataChange=Intent(BRODCAST_USER_DATA_CHANGE)
                        LocalBroadcastManager.getInstance(this).sendBroadcast(
                            userDataChange
                        )
                        enableSpinner(false)
                        finish()

接收端:

First register LocalBroadcast Receiver Then handle incoming intent data in 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);

我更愿意全面地回答。

LocalbroadcastManager included in android 3.0 and above so you have to use support library v4 for early releases. see instructions here Create a broadcast receiver: 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 !"); } }; Register your receiver in onResume of activity like: 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. unRegister receiver in onPause: protected void onPause() { super.onPause(); LocalBroadcastManager.getInstance(this).unregisterReceiver(onNotice); } Now whenever a localbroadcast is sent from applications' activity or service, onReceive of onNotice will be called :).

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

如何将全局广播更改为局部广播

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);