gpt4 book ai didi

android - 如何使用本地广播管理器?

转载 作者:IT老高 更新时间:2023-10-28 12:49:03 33 4
gpt4 key购买 nike

如何使用/定位 LocalBroadcastManager,如 google docs 中所述和 Service broadcast doc ?

我尝试用谷歌搜索,但没有可用的代码?

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

任何帮助/评论?

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

最佳答案

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

ReceiverActivity.java

监视名为 "custom-event-name" 的事件通知的 Activity .

@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

发送/广播通知的第二个 Activity 。

@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 被广播并被 mMessageReceiver 接收在 ReceiverActivity .

调试输出应如下所示:

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!

关于android - 如何使用本地广播管理器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8802157/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com