Forum Xamarin.Android

Accessing Prism Registered Services from Android BroadcastReceiver

nirkbirknirkbirk Member
edited August 2019 in Xamarin.Android


I've run into an issue while implementing notifications in an app I'm developing. I'm using Prism alongside Xamarin Forms (please let me know if this question should be moved to that forum instead).

Everything works fine so far, but due to Android clearing all alarms on a reboot, I've had to implement a BroadcastReceiver listening for BOOT_COMPLETED that handles recreating the alarm intents responsible for delivering the notifications at certain times.

However, after rebooting the device, the BroadcastReceiver is hit, but Prism.PrismApplicationBase.Current returns null, which I assume is because the app itself is not being initialised?

Here is the broadcast receiver code which handles the boot logic. This works fine if the App has already been run and I trigger the BOOT_COMPLETED event through adb using 'adb shell am broadcast'.

    [BroadcastReceiver(Name = "", Enabled = true)]
    [IntentFilter(new[] { Intent.ActionBootCompleted })]
    public class BootReceiver : BroadcastReceiver
        public override void OnReceive(Context context, Intent intent)
                var container = (Prism.PrismApplicationBase.Current as Prism.Unity.PrismApplication).Container;
                var manager = container.Resolve(typeof(INotificationManager)) as INotificationManager;

            catch (Exception ex)
                Log.Error("myapp", Java.Lang.Throwable.FromException(ex), "Error in bootreceiver");

The notification manager is registered in the App.xaml.cs along with all the other cross-platform service registrations

I am clearly missing something here! Is there a solution to this problem, or am I misunderstanding how BroadcastReceivers work?

I really don't want to manually build the dependency tree required to instantiate a NotificationManager object in the OnReceive method of my BootReceiver class if it can at all be avoided.

Thanks in advance.

Sign In or Register to comment.