如何使用广播发送数据

How to send data using broadcast

我正在使用

发送广播
Intent intent = new Intent();
intent.setAction("com.example.android.name");
intent.putExtra("CODE", code);

onReceive广播侦听器class方法中使用

检索额外数据
String code = intent.getStringExtra("CODE");

我收到空指针异常。 任何帮助如何检索数据。

public class ReceiveNetworkBroadcast extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        Bundle extras = intent.getExtras();
        String code = extras.getString("CODE");
        Log.e("NET_BCAST_RECEIVER: ", code); 

    }

}

       <receiver
            android:name=".ReceiveNetworkBroadcast"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.example.android.name" />
            </intent-filter>
        </receiver>

public void sendBroadcast(Context context, String code){
        Intent intent = new Intent();
        intent.setAction("com.example.android.name");
        intent.putExtra("CODE", code);
        intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
        context.sendBroadcast(intent);

    }

尝试像这样在 bundle 中获得 Intent 额外内容:

@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub
    Bundle extras = intent.getExtras();
     if (extras != null) {
      if(extras.containsKey("CODE")){
       Object value=extras.get("CODE");
       System.out.println(value);
      }
     }

}

希望它现在能起作用。