dotnetco.de

Check whether Push is enabled in Xamarin Forms iOS and Android

If you have implemented Push Notifications in your Xamarin Forms iOS and Android app (maybe as explained in Setup Xamarin Forms for iOS Push Notifications or Setup Xamarin Forms Android App for Push Notifications), you might also want to know whether user has enabled Push Notifications in his system settings so you could show a warning in case it’s disabled. As this is OS specific, there is no Xamarin Forms implementation but you could create some easy interfaces to check the status. The code is based on Evan Parsons’ code for iOS and Rene Rupperts lines for Android, so thanks to both!

New Interface in Xamarin Forms

First, in your Xamarin Forms PCL, create a new Interface called INotificationsInterface:

using System;
namespace MyApp.Helpers
{
    public interface INotificationsInterface
    {
        bool registeredForNotifications();
    }
}

 

Add class to Android

Now add a new class in your Xamarin Forms Android Application:

using System;
using Android.Support.V4.App;
using Xamarin.Forms;

[assembly: Dependency(typeof(MyApp.Droid.NotificationsInterface))]
namespace MyApp.Droid
{
    public class NotificationsInterface : MyApp.Helpers.INotificationsInterface
    {
        public bool registeredForNotifications()
        {
            var nm = NotificationManagerCompat.From(Android.App.Application.Context);
            bool enabled = nm.AreNotificationsEnabled();
            return enabled;
        }
    }
}

 

Add class to iOS

Next, add a new class in your Xamarin Forms iOS Application:

using System;
using UIKit;
using Xamarin.Forms;

[assembly: Dependency(typeof(MyApp.iOS.NotificationsInterface))]
namespace MyApp.iOS
{
    public class NotificationsInterface : MyApp.Helpers.INotificationsInterface
    {
        public bool registeredForNotifications()
        {
            UIUserNotificationType types = UIApplication.SharedApplication.CurrentUserNotificationSettings.Types;
            if (types.HasFlag(UIUserNotificationType.Alert))
            {
                return true;
            }
            return false;
        }
    }
}

 

 

Now check whether push is enabled

Finally, call the DependencyService in your application code in Xamarin Forms:

bool isPushEnabled;
try
{
    isPushEnabled = DependencyService.Get<Helpers.INotificationsInterface>().registeredForNotifications();
    Debug.WriteLine(@"Push enabled on current device: {0}.", isPushEnabled.ToString());
}
catch (Exception ex)
{
    Debug.WriteLine(@"Error checking whether push is allowed: {0}", ex.Message);
    isPushEnabled = true;
}

 

If anything went wrong, I set isPushEnabled to true because I don’t want to bother the user with a warning even though he maybe has push already enabled but my app was (for whatever reason) not able to find out.

That’s it already!

5 Comments

Leave a Comment