如何使用LocalBroadcastManager?

480
如何使用/定位在Google文档服务广播文档中描述的LocalBroadcastManager
我尝试谷歌搜索,但没有可用的代码起点?
文档说如果我想在我的应用程序进程内部进行广播,则应该使用它,但是我不知道要查找哪里。
有任何帮助/评论吗?
更新:我知道如何使用广播,但不知道如何在项目中获得LocalBroadcastManager

Waqas,你在清单中注册了接收器吗?如果是,请告诉我如何操作? - Mudassir
2
我认为您不需要在清单中注册接收器来接收此类广播,因为如果这样做,那么该接收器也将监听全局广播。 - waqaslam
3
是的。这意味着我必须按照下面的答案中给出的代码进行操作:LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("custom-event-name")); - Mudassir
2
LocalBroadcastManager已被弃用。我用更好的EventBus库替换了它,个人认为这样更好。 - Kris B
13个回答

0
在您的 AndroidManifest.xml 文件中通过使用 标签(也称为静态标签)声明一个。
<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>

您会注意到上面声明的广播接收器具有属性exported =“true”。该属性告诉接收器它可以接收应用程序范围之外的广播。
2. 或通过使用registerReceiver(也称为上下文注册)动态地注册实例。

public abstract Intent registerReceiver (BroadcastReceiver receiver, 
            IntentFilter filter);

public void onReceive(Context context, Intent intent) {
//Implement your logic here
}

发送广播有三种方式:
sendOrderedBroadcast方法确保一次只向一个接收器发送广播。每个广播可以依次将数据传递给其后面的广播,或停止将广播传播到后续的接收器。
sendBroadcast与上述方法类似,唯一的区别在于所有广播接收器都会接收消息,彼此之间不依赖。
LocalBroadcastManager.sendBroadcast方法仅向应用程序内定义的接收器发送广播,并且不超出应用程序的范围。


0

我是一名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)

-4

我们也可以使用接口来实现与广播管理器相同的功能,这里我分享了使用接口的 broadcastManager 测试代码。

首先创建一个接口:

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

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

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

因此,通过这种方法,我们可以使用与广播管理器相同的接口功能。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接