我的应用程序发生了一些奇怪的事情。 我正在尝试通过执行以下操作通过广播发送字符串:
第一步(发送):
Intent intent = new Intent("INFO");
intent.putExtra("INFO_VALUE", "hello_world_2019");
第二步(接收):
if ("INFO".equals(intent.getAction())) {
String abc = intent.getStringExtra("INFO_VALUE");
Log.i(TAG, "" + abc);
}
执行上述步骤后,我在abc
字段中输入了空值。另外,如果我使用调试器并检查与第二步相关的意图,则会得到:
intent -> mExtras -> mMap -> value[0] -> name: "hello_world_2019"
我对正在发生的事情感到困惑。 abc
字段不应为空,但在这种情况下为空。
如何填充上述字段,使其不为null?
答案 0 :(得分:0)
请解释一下您到底想做什么,如果您想将数据从一项活动发送给我的朋友以外的其他人,这不是正确的方法。
如果要发送广播并在代码内的某处接收该广播,则需要执行以下步骤:
ReceiverActivity.java
@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("INFO"));
}
// 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
private void sendMessage() {
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("INFO");
// You can also include some extra data.
intent.putExtra("message", "Message goes here!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}