广播接收器未激活

时间:2018-05-24 13:26:10

标签: android broadcastreceiver

从外部通信接收数据后,我想通过广播发送数据,以便在屏幕上打印。

以下是我的服务部分将数据发送到广播:

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也从未激活过。你能帮帮我吗?

1 个答案:

答案 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");
        }
};