【问题标题】:Disappearing string in intent意图中消失的字符串
【发布时间】:2018-12-18 16:59:48
【问题描述】:

我的应用程序发生了一些奇怪的事情。 我正在尝试通过执行以下操作通过广播发送字符串:

第一步(发送):

    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 字段不应该为空,但在这种情况下是这样。

如何填充上述字段使其不为空?

【问题讨论】:

  • edit 提供一个minimal reproducible example 来证明问题。
  • 请说明Intent 如何从第一个代码 sn-p 到第二个代码。这个Intent 是直接在sendBroadcast() 调用中使用的吗?或者它是否包含在其他地方使用的PendingIntent 中?我们需要更多背景信息来帮助您。您发布的代码看起来不错,问题出在其他地方。

标签: java android android-intent broadcastreceiver


【解决方案1】:

请解释一下你到底想做什么,如果你想从一个活动向我的朋友以外的人发送数据,这不是正确的方法。

如果您想发送广播并在代码中的某处接收该广播,则需要执行以下步骤:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-04
    • 2018-08-02
    • 2012-07-06
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多