Search code examples
androidandroid-intentbroadcastreceiver

How does a manifest registered BroadcastReceiver interact with other objects?


I have a manifest registered BroadcastReceiver which receives repeat alarms from an AlarmManager, I want to notify a Service when an alarm received, I'm thinking about set a listener to the BroadcastReceiver and call the listener like this:

public class HeartbeatAlarmReceiver extends BroadcastReceiver {

    private OnAlarmReceivedListener mListener;

    public interface OnAlarmReceivedListener {
        /**
         * Callback to call when a heart beat alarm received.
         */
        public void onHeartBeatAlarmReceived();
    }

    public HeartbeatAlarmReceiver(OnAlarmReceivedListener listener) {
        mListener = listener;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        mListener.onHeartBeatAlarmReceived();
    }
}

However, this requires a constructor with parameter to set the listener, but manifest registered BroadcastReceiver seems to be initiated by a default constructor. I know I can register the receiver in the code by giving an IntentFilter, but for some reason I must use an explicit Intent to start the receiver, which means I must declare it in the manifest. (see this) so what should I do?


Solution

  • You have two options:

    1. Your BroadcastReceiver can call your service. Use context.startService(intent).
    2. When you make the PendingIntent for your alarm, you can make it for the Service directly instead of for the BroadcastReceiver. Use PendingIntent.getService(...)