我正在使用发送广播
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/