Search code examples
androidbroadcastreceiver

Broadcast Receiver is not activated


After receiving a data from an external communication, I want to send it on broadcast in order to print it on screen.

Here is the part of my service that sends the data into broadcast:

Intent intent = new Intent("CodeFilter_MemoryRead"); 
intent.putExtra("data_memory_read_from_hce", MemoryStringValue);
this.sendBroadcast(intent);

And the activity that is meant to receive it:

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

The issue I have is that my BroadcastReceiver is never activated even after the command this.sendBroadcast(intent). Can you help me please?


Solution

  • The string you create the Intent with doesn't match the string you add to IntentFilter. They need to be the same in order for the receiver to receive the intent. The following code should work:

    Intent intent = new Intent("CodeFilter_MemoryRead"); 
    intent.putExtra("data_memory_read_from_hce", MemoryStringValue);
    this.sendBroadcast(intent);
    

    and

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