如何使用LocalBroadcastManager?

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

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

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

任何帮助/评论?

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

266767 次浏览

我还是要回答这个问题。以防有人需要。

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就会被广播并被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中,最终我不得不通过右键单击我的项目并选择兼容性/支持库来添加:

__abc0 __abc1 __abc2

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


Android Compatibility Library

我更愿意全面地回答。

  1. LocalbroadcastManager包含在android3.0及以上,所以你有 为早期版本使用支持库v4。参见 李在这里 < / p > < / >

  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. 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.
    
  4. unRegister receiver in onPause:

    protected void onPause() {
    super.onPause();
    LocalBroadcastManager.getInstance(this).unregisterReceiver(onNotice);
    }
    
  5. Now whenever a localbroadcast is sent from applications' activity or service, onReceive of onNotice will be called :).

Edit: You can read complete tutorial here LocalBroadcastManager: Intra application message passing

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

EDIT:该链接已从网站上删除,但数据如下: https://github.com/carrot-garden/android_maven-android-plugin-samples/blob/master/support4demos/src/com/example/android/supportv4/content/LocalServiceBroadcaster.java < / p >

我们也可以使用接口相同的broadcastManger在这里我分享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);
}
}

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

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

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

当你玩够了LocalBroadcastReceiver,我会建议你试试绿色机器人的EventBus——你一定会意识到它与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
    }
    }
    };
    

On Sending End:

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


LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

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

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

Localbroadcastmanager已弃用,请改用可观察模式的实现。

__abc0 __abc1 __abc2

原因

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对象不处于活动状态,则observer 即使值改变也不会被调用。

  • Lifecycle对象被销毁后,观察者为 李自动删除< / p > < / >

事实上,LiveData对象是生命周期感知的,这意味着你可以在多个活动、片段和服务之间共享它们。

enter code here if (createSuccses){
val userDataChange=Intent(BRODCAST_USER_DATA_CHANGE)
LocalBroadcastManager.getInstance(this).sendBroadcast(
userDataChange
)
enableSpinner(false)
finish()

通过在AndroidManifest.xml文件中声明一个标签(也称为static)

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

你会注意到上面声明的广播接收器有一个属性export = " true "。这个属性告诉接收者它可以接收来自应用程序作用域之外的广播 2. 或者通过向registerReceiver动态注册一个实例(也就是所谓的context registered)

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


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

有三种方式发送广播:
sendOrderedBroadcast方法确保一次只向一个接收器发送广播。每个广播可以依次将数据传递给后面的广播,或者停止广播向后面的接收器的传播 sendBroadcast与上面提到的方法类似,只有一个区别。
.
.
. LocalBroadcastManager。sendBroadcast方法只向应用程序内定义的接收器发送广播,不超出应用程序的范围

使用LocalBroadcastManager的Kotlin版本:

请检查下面的代码registeringsendingreceiving broadcast消息

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)