Skip to content

Latest commit

 

History

History
300 lines (199 loc) · 11.7 KB

GettingStarted.md

File metadata and controls

300 lines (199 loc) · 11.7 KB

Starting with Android

Android Configuration

First, make sure you setup everthing on Firebase portal and Azure portal.

Also add this permission:

<uses-permission android:name="android.permission.INTERNET" />

Add google-services.json to Android project. Make sure build action is GoogleServicesJson

ADD JSON

Must compile against 26+ as plugin is using API 26 specific things. Here is a great breakdown: http://redth.codes/such-android-api-levels-much-confuse-wow/ (Android project must be compiled using 8.0+ target framework)

Android Initialization

You should initialize the plugin on an Android Application class if you don't have one on your project, should create an application class. Then call AzurePushNotificationManager.Initialize method on OnCreate.

There are 3 overrides to AzurePushNotificationManager.Initialize:

  • AzurePushNotificationManager.Initialize(Context context,string notificationHubConnectionString,string notificationHubPathName, bool resetToken,bool autoRegistration) : Default method to initialize plugin without supporting any user notification categories. Uses a DefaultPushHandler to provide the ui for the notification.

  • AzurePushNotificationManager.Initialize(Context context,string notificationHubConnectionString,string notificationHubPathName, NotificationUserCategory[] categories, bool resetToken,bool autoRegistration) : Initializes plugin using user notification categories. Uses a DefaultPushHandler to provide the ui for the notification supporting buttons based on the action_click send on the notification

  • AzurePushNotificationManager.Initialize(Context context,string notificationHubConnectionString,string notificationHubPathName,IPushNotificationHandler pushHandler, bool resetToken,bool autoRegistration) : Initializes the plugin using a custom push notification handler to provide custom ui and behaviour notifications receipt and opening.

Important: While debugging set resetToken parameter to true.

Example of initialization:

    [Application]
    public class MainApplication : Application
    {
        public MainApplication(IntPtr handle, JniHandleOwnership transer) :base(handle, transer)
        {
        }

        public override void OnCreate()
        {
            base.OnCreate();
	    
	    //Set the default notification channel for your app when running Android Oreo
            if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
            {
                //Change for your default notification channel id here
                AzurePushNotificationManager.DefaultNotificationChannelId = "DefaultChannel";

                //Change for your default notification channel name here
                AzurePushNotificationManager.DefaultNotificationChannelName = "General";
            }
            
            //If debug you should reset the token each time.
            #if DEBUG
              AzurePushNotificationManager.Initialize(this,"Notification Hub Connection String","Notification Hub Path Name",true);
            #else
              AzurePushNotificationManager.Initialize(this,"Notification Hub Connection String","Notification Hub Path Name",false);
            #endif

              //Handle notification when app is closed here
              CrossAzurePushNotification.Current.OnNotificationReceived += (s,p) =>
              {


              };

	  
         }
    }

By default the plugin launches the main launcher activity when you tap at a notification, but you can change this behaviour by setting the type of the activity you want to be launch on AzurePushNotificationManager.NotificationActivityType

If you set AzurePushNotificationManager.NotificationActivityType then put the following call on the OnCreate of activity of the type set. If not set then put it on your main launcher activity OnCreate method (On the Activity you got MainLauncher= true set)

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

			//Other initialization stuff

            AzurePushNotificationManager.ProcessIntent(this,Intent);
        }

Note: When using Xamarin Forms do it just after LoadApplication call.

By default the plugin launches the activity where ProcessIntent method is called when you tap at a notification, but you can change this behaviour by setting the type of the activity you want to be launch on AzurePushNotificationManager.NotificationActivityType

You can change this behaviour by setting AzurePushNotificationManager.NotificationActivityFlags.

If you set AzurePushNotificationManager.NotificationActivityFlags to ActivityFlags.SingleTop or using default plugin behaviour then make this call on OnNewIntent method of the same activity on the previous step.

       protected override void OnNewIntent(Intent intent)
       {
           base.OnNewIntent(intent);
           AzurePushNotificationManager.ProcessIntent(this,intent);
       }

More information on AzurePushNotificationManager.NotificationActivityType and AzurePushNotificationManager.NotificationActivityFlags and other android customizations here:

Android Customization

Starting with iOS

First, make sure you set everything on Apple Developer Portal and Azure portal. You can follow this guide:

https://docs.microsoft.com/en-us/azure/notification-hubs/notification-hubs-push-notification-http2-token-authentification

iOS Configuration

On Info.plist enable remote notification background mode

Remote notifications

iOS Initialization

There are 3 overrides to AzurePushNotificationManager.Initialize:

  • AzurePushNotificationManager.Initialize(string notificationHubConnectionString,string notificationHubPathName, NSDictionary options,bool autoRegistration,bool autoRegistration, bool enableDelayedResponse) : Default method to initialize plugin without supporting any user notification categories. Auto registers for push notifications if second parameter is true.

  • AzurePushNotificationManager.Initialize(string notificationHubConnectionString,string notificationHubPathName,NSDictionary options, NotificationUserCategory[] categories,bool autoRegistration, bool enableDelayedResponse) : Initializes plugin using user notification categories to support iOS notification actions.

  • AzurePushNotificationManager.Initialize(string notificationHubConnectionString,string notificationHubPathName,NSDictionary options,IPushNotificationHandler pushHandler,bool autoRegistration, bool enableDelayedResponse) : Initializes the plugin using a custom push notification handler to provide native feedback of notifications event on the native platform.

Call AzurePushNotificationManager.Initialize on AppDelegate FinishedLaunching

AzurePushNotificationManager.Initialize("Notification Hub Connection String","Notification Hub Path Name",options,true);

Note: When using Xamarin Forms do it just after LoadApplication call.

Also should override these methods and make the following calls:

        public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
        {
             AzurePushNotificationManager.DidRegisterRemoteNotifications(deviceToken);
        }

        public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)
        {
            AzurePushNotificationManager.RemoteNotificationRegistrationFailed(error);

        }
        // To receive notifications in foregroung on iOS 9 and below.
        // To receive notifications in background in any iOS version
        public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
        {
            
            AzurePushNotificationManager.DidReceiveMessage(userInfo);
        }

      

Using Push Notification APIs

It is drop dead simple to gain access to the PushNotification APIs in any project. All you need to do is get a reference to the current instance of IPushNotification via CrossPushNotification.Current:

Register tags

   /// <summary>
   /// Registers tags in Azure Notification hub
   /// </summary>
    await CrossAzurePushNotification.Current.RegisterAsync(new string[]{"crossgeeks","general"});

Note: The method above cleans all previous registered tags when called. So it kind of replaces the tags each time you call it.

Unregister tags

   /// <summary>
   /// Unregister all tags in Azure Notification hub
   /// </summary>
    await CrossAzurePushNotification.Current.UnregisterAsync();

On Demand Registration

When plugin initializes by default auto request permission the device for push notifications. If needed you can do on demand permisssion registration by turning off auto registration when initializing the plugin.

Use the following method for on demand permission registration:

   CrossAzurePushNotification.Current.RegisterForPushNotifications();

Events

Once token is registered/refreshed you will get it on OnTokenRefresh event.

   /// <summary>
   /// Event triggered when token is refreshed
   /// </summary>
    event AzurePushNotificationTokenEventHandler OnTokenRefresh;

Note: Don't call RegisterAsync in the event above because it is called automatically each time the token changes

  /// <summary>
  /// Event triggered when a notification is received
  /// </summary>
  event AzurePushNotificationResponseEventHandler OnNotificationReceived;
  /// <summary>
  /// Event triggered when a notification is opened
  /// </summary>
  event AzurePushNotificationResponseEventHandler OnNotificationOpened;
   /// <summary>
   /// Event triggered when a notification is deleted (Android Only)
   /// </summary>
   event AzurePushNotificationDataEventHandler OnNotificationDeleted;
  /// <summary>
  /// Event triggered when there's an error
  /// </summary>
  event AzurePushNotificationErrorEventHandler OnNotificationError;

Token event usage sample:

  CrossAzurePushNotification.Current.OnTokenRefresh += (s,p) =>
  {
        System.Diagnostics.Debug.WriteLine($"TOKEN : {p.Token}");
  };

Push message received event usage sample:

  CrossAzurePushNotification.Current.OnNotificationReceived += (s,p) =>
  {
 
        System.Diagnostics.Debug.WriteLine("Received");
    
  };

Push message opened event usage sample:

  
  CrossAzurePushNotification.Current.OnNotificationOpened += (s,p) =>
  {
                System.Diagnostics.Debug.WriteLine("Opened");
                foreach(var data in p.Data)
                {
                    System.Diagnostics.Debug.WriteLine($"{data.Key} : {data.Value}");
                }

                if(!string.IsNullOrEmpty(p.Identifier))
                {
                    System.Diagnostics.Debug.WriteLine($"ActionId: {p.Identifier}");
                }
             
 };

Push message deleted event usage sample: (Android Only)

  CrossAzurePushNotification.Current.OnNotificationDeleted+= (s,p) =>
  {
 
        System.Diagnostics.Debug.WriteLine("Deleted");
    
  };

Plugin by default provides some notification customization features for each platform. Check out the Android Customization and iOS Customization sections.

<= Back to Table of Contents