从外部通信接收数据后,我想通过广播发送数据,以便在屏幕上打印。
以下是我的服务部分将数据发送到广播:
Intent intent = new Intent("CodeFilter_MemoryRead");
intent.putExtra("data_memory_read_from_hce", MemoryStringValue);
this.sendBroadcast(intent);
以及接收它的活动:
@Override
protected void onStart() {
super.onStart();
final IntentFilter hceNotificationsFilter = new IntentFilter();
hceNotificationsFilter.addAction("CodeFilter");
registerReceiver(hceNotificationsReceiver, hceNotificationsFilter);
}
final BroadcastReceiver hceNotificationsReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String hcedata = intent.getExtras().toString();
RealMessageReceived.setText(hcedata);
Log.i(TAG, "Broadcast listener activated");
}
};
我遇到的问题是,即使在命令this.sendBroadcast(intent)
之后,我的BroadcastReceiver也从未激活过。你能帮帮我吗?
答案 0 :(得分:0)
您创建Intent
的字符串与您添加到IntentFilter
的字符串不匹配。它们需要相同才能使接收者接收意图。以下代码应该有效:
Intent intent = new Intent("CodeFilter_MemoryRead");
intent.putExtra("data_memory_read_from_hce", MemoryStringValue);
this.sendBroadcast(intent);
和
@Override
protected void onStart() {
super.onStart();
final IntentFilter hceNotificationsFilter = new IntentFilter();
hceNotificationsFilter.addAction("CodeFilter_MemoryRead");
registerReceiver(hceNotificationsReceiver, hceNotificationsFilter);
}
final BroadcastReceiver hceNotificationsReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String hcedata = intent.getExtras().toString();
RealMessageReceived.setText(hcedata);
Log.i(TAG, "Broadcast listener activated");
}
};