android - 如何使用广播发送数据

标签 android broadcastreceiver

我正在使用发送广播

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

在广播监听器类的onReceive方法中使用检索额外数据时

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

}

希望它现在能起作用。

关于android - 如何使用广播发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34724313/

相关文章:

java - 在运行时在微调器中添加项目

android - 从 Android 模拟器访问 IIS Express

android - ACTION_MEDIA_BUTTON 在 BroadcastReceiver 中不起作用

android - 为什么通知在android通知栏中出现一段时间然后消失

android - 如何在 Exoplayer 中只缓存 DASH 的第一段?

android - 设备处于低功耗模式时 SystemClock.elapsedRealtime() 漂移

Android SensorDirectChannel 不返回任何传感器测量结果

android - 如何借助广播接收器检测来电?

android - 以编程方式注册广播接收器

android oreo 在服务中获取来电号码