如何使用/定位在谷歌文档和服务广播文档中描述的LocalBroadcastManager ?
我试着谷歌它,但没有可用的代码开始?
文档说,我应该使用它,如果我想做广播内部与我的应用程序的进程,但我不知道在哪里寻找这个。
任何帮助/评论?
更新:我知道如何使用广播,但不知道如何在我的项目中获得LocalBroadcastManager。
如何使用/定位在谷歌文档和服务广播文档中描述的LocalBroadcastManager ?
我试着谷歌它,但没有可用的代码开始?
文档说,我应该使用它,如果我想做广播内部与我的应用程序的进程,但我不知道在哪里寻找这个。
任何帮助/评论?
更新:我知道如何使用广播,但不知道如何在我的项目中获得LocalBroadcastManager。
当前回答
我还是要回答这个问题。以防有人需要。
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!
其他回答
我还是要回答这个问题。以防有人需要。
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!
一个实现LocalBroadcastManager的Activity和Service的例子可以在开发者文档中找到。我个人觉得它非常有用。
编辑:该链接已从网站上删除,但数据如下: https://github.com/carrot-garden/android_maven-android-plugin-samples/blob/master/support4demos/src/com/example/android/supportv4/content/LocalServiceBroadcaster.java
如何将全局广播更改为局部广播
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的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()
}
}
Localbroadcastmanager已弃用,请改用可观察模式的实现。
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对象被销毁之后,观察者就被销毁了 自动删除
LiveData对象能够感知生命周期这一事实意味着您可以在多个活动、片段和服务之间共享它们。