Xamarin

Add Xtremepush to both iOS and Android apps built with Xamarin

Xtremepush supports push notifications for iOS devices via Apple's Push Notification Service (APNs) and push notifications for Android devices via Google’s FCM (Firebase Cloud Messaging for Android) service. This page contains Xamarin-specific instructions but you will need to connect your iOS and Android app to the platform separately.

Before integrating

To complete this integration you will need to have your Xtremepush app key, APNS certs for iOS and Google project number and FCM API key for Android. These are used to connect your app to the platform and the Apple and Google push services. Review our guides on connecting to the platform below:

👍

Xamarin forms

This page provides a full Xamarin integration guide for Android and iOS. If you are using Xamarin.Forms, you must complete the integration for each platform as described in the Xamarin.Forms guide and then you must also follow the steps outlined here.

Android

  • To save the google-services.json file associated with your project follow the steps under Get configuration values in the Android push notifications guide.
  • Download the latest Xtremepush Xamarin bindings DLL file from Xamarin SDK releases.
  • In your IDE (Visual Studio or Xamarin Studio), add a reference in your app project to the DLL file:
    • Edit References > .Net Assembly > Browse... > Select the DLL

  • In your IDE, add two additional packages to the project to satisfy the underlying dependencies of our SDK: 
    • Google Play Services - Location (latest stable NuGet package currently 120.0.0.1)
    • GoogleGson -  (latest stable NuGet package currently 2.10.1.2)
    • Xamarin.Firebase.Messaging (latest stable NuGet package currently 123.1.1.1)
  • Edit the AndroidManifest.xml file to add the following elements within the manifest element.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />   
  <uses-permission android:name="android.permission.INTERNET" />
	<uses-permission android:name="android.permission.WAKE_LOCK" />
 <permission android:name=".permission.C2D_MESSAGE" android:protectionLevel="signature" />
   
  • In the event you are using Location or Beacon functionality, you will need to add the following into the manifest element as well.
	<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" android:exported="false"  />
	<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" android:exported="false" />
	<uses-feature android:name="android.hardware.bluetooth_le" android:required="false" />
	<uses-permission android:name="android.permission.BLUETOOTH" android:required="false" />
	<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:required="false" />
	<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" android:exported="false"/>
	<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" android:exported="false" />
  • Edit the AndroidManifest.xml file to add the following elements within the application element.
<activity android:name="ie.imobile.extremepush.ui.InboxActivity" android:configChanges="orientation|screenSize" android:label="@string/title_activity_inbox" android:theme="@style/Theme.Transparent" />
		<activity android:name="ie.imobile.extremepush.ui.OnclickPushActivity" android:exported="false" android:taskAffinity="" />
		<service android:name="ie.imobile.extremepush.NotificationOnClickHandlerService" />
		<activity android:name="ie.imobile.extremepush.ui.WebViewActivity" android:exported="false" />
		<activity android:name="ie.imobile.extremepush.ui.LocationDialogActivity" android:exported="false" android:label="Locations are not available" android:theme="@android:style/Theme.Dialog" />
		<!-- REQUIRED FOR GEO LOCATION SERVICES -->
		<service android:name="ie.imobile.extremepush.location.GeoLocationService" />
		<!-- REQUIRED FOR IBEACON -->
		<service android:name="ie.imobile.extremepush.beacons.BeaconLocationService" />
		<!-- REQUIRED FOR GCM, LOCATION AND BEACON -->
		<receiver android:name="ie.imobile.extremepush.receivers.CoreBroadcastReceiver" android:exported="false">
			<intent-filter>
				<action android:name="ie.imobile.extremepush.BEACON_SERVICE_STARTED" />
				<category android:name="." />
			</intent-filter>
			<intent-filter>
				<action android:name="android.intent.action.BOOT_COMPLETED" />
				<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
				<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
			</intent-filter>
		</receiver>
		<service android:name="ie.imobile.extremepush.beacons.XPBeaconJobService" android:permission="android.permission.BIND_JOB_SERVICE" />
		<service android:name="ie.imobile.extremepush.util.ImageHandlerJobService" android:permission="android.permission.BIND_JOB_SERVICE" />
		<receiver android:name="ie.imobile.extremepush.beacons.BeaconLocationReceiver" android:exported="false" />
		<receiver android:name="ie.imobile.extremepush.location.GeoLocationBroadcastReceiver" android:exported="false" />
		<receiver android:name="ie.imobile.extremepush.location.ProxymityAlertReceiver" android:exported="false" />
		<receiver android:name="ie.imobile.extremepush.receivers.XP_App_Update_Receiver" android:exported="false">
			<intent-filter>
				<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
				<category android:name="." />
			</intent-filter>
		</receiver>
		<service android:name="ie.imobile.extremepush.google.XPFirebaseMessagingService" android:exported="false">
			<intent-filter>
				<action android:name="com.google.firebase.MESSAGING_EVENT" />
			</intent-filter>
		</service>
  • Edit the AndroidManifest.xml file to make sure there is an icon set within the application element. This is required for the correct generation of notifications.
<application android:icon="@mipmap/icon" android:label="@string/app_name">
  • In the root C# file of your project, pull in the Xtremepush library:
using IE.Imobile.Extremepush;
using IE.Imobile.Extremepush.Api.Model;
  • You may require some of the following packages in the same file, if not imported already:
using Android.App;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using System;
using System.Collections.Generic;
  • Add the google-services.json you downloaded to your project.
    1. Copy google-services.json to the project folder.
    2. Add google-services.json to the app project.
    3. Right-click google-services.json.
    4. Set the Build Action to GoogleServicesJson.

  • Override the Application onCreate function to initialise the Xtremepush SDK. Set the SDK key to the one provided when adding the app to the platform, and the Google Project Number with the one found in the earlier steps setting up Android Push Notifications. This example also shows how you can register a callback for message response events, and register a callback when the inbox badge is updated.
[Application]
public class MainApp : Application, IMessageResponseListener, IInboxBadgeUpdateListener
{
    public MainApp(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
    {
    }

    public void MessageResponseReceived(Message messagePayload,
                                    IDictionary<string, string> responsePayload,
                                    Java.Lang.Ref.WeakReference activityHolder)
    {
        // Handle a message response
        if (messagePayload != null)
        {
            Log.Debug("MessageResponseReceived", messagePayload.ToJson());
        }
        if (responsePayload != null)
        {
            foreach (KeyValuePair<string, string> keypair in responsePayload)
                Log.Debug("MessageResponseReceived", keypair.Key + " - " + keypair.Value);
        }
    }

    public void InboxBadgeUpdated(int i, Java.Lang.Ref.WeakReference activityHolder)
    {
        //print out inbox badge 
        Log.Debug("Inbox Badge is : ", i + "");
    }

    public override void OnCreate()
    {
        base.OnCreate();
        // If using Xamarin.Forms please install the Plugin.CurrentActivity package
        // from NuGet and uncomment the line below
        // CrossCurrentActivity.Current.Init(this);
        String XPUSH_APP_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        String GOOGLE_PROJECT_NUMBER = "XXXXXXXXXXXX";
        new PushConnector.Builder(XPUSH_APP_KEY, GOOGLE_PROJECT_NUMBER)
                            .SetMessageResponseListener(this)
                            .SetInboxBadgeUpdateListener(this)
                            .Create(this);
    }
}
  • If you want to send tags or events to Xtremepush elsewhere in your app, this can be achieved with the following function calls:
PushConnector.MPushConnector.HitTag("TestTag");
PushConnector.MPushConnector.HitEvent("TestEvent");

iOS

  • Download the latest Xtremepush Xamarin bindings DLL file from Xamarin SDK releases.
  • In your IDE (Visual Studio or Xamarin Studio), add a reference in your app project to the DLL file
    • Edit References > .Net Assembly > Browse... > Select the DLL

  • In the Source view of the Info.plist file, set the following parameters:
    • XtremePushApplicationKey – the SDK application key provided when adding the app to the platform.
    • NSBluetoothPeripheralUsageDescription – a required usage description you have to add to your app as the Xtremepush SDK includes CoreBluetooth (even if it is not actively used). See Add description for CoreBluetooth for further information.
    • If using location/beacon functionality in your app, make sure that you have entries for NSLocationAlwaysUsageDescriptionNSLocationAlwaysAndWhenInUseUsageDescription and NSLocationWhenInUseUsageDescription.

  • Edit the AppDelegate.cs file and add the following lines inside the FinishedLaunching() function:
using XP;

// Setup xtremepush
XPush.RegisterForRemoteNotificationTypes(XPNotificationType.Alert | XPNotificationType.Badge | XPNotificationType.Sound);

XPush.SetSandboxModeEnabled(true); //Required if doing a debug/dev build of your app
XPush.SetLocationEnabled(true); // Required for location or beacon functionality

XPush.RegisterMessageResponseHandler((XPMessageResponse response) =>
{
   ///handle received message. For example:
   Console.WriteLine("Response with identifier: " + response.Message.CampaignIdentifier);
   Console.WriteLine("Response with type: " + response.Message.Type);
   Console.WriteLine("Response with action URL: " + response.Action.Url);
   
   ////Check out XPMessage and XPAction declarations for more avaliable fields
});

NSNotificationCenter.DefaultCenter.AddObserver(Constants.XPushInboxBadgeChangeNotification, InboxBadgeUpdated);

XPush.ApplicationDidFinishLaunchingWithOptions((options != null) ? options : new NSDictionary());
  • Add the following function to the AppDelegate.cs file if you want to handle inbox badge updated events:
public void InboxBadgeUpdated(NSNotification nu){
    Console.WriteLine("Inbox Badge Changed : " + XP.XPush.InboxBadge);
}
  • Edit the AppDelegate.cs file and add the following callbacks to the Xtremepush SDK:
public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
    XP.XPush.ApplicationDidRegisterForRemoteNotificationsWithDeviceToken(deviceToken);
}

public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)
{
    XP.XPush.ApplicationDidFailToRegisterForRemoteNotificationsWithError(error);
}
  • If you need to associate an Apple ID with your IDE, do this now in the IDE preferences:

  • Edit the Entitlements.plist file to enable push notifications.

  • If you are not using Xamarin.Forms and want to send tags or events to Xtremepush elsewhere in your app, this can be achieved with the following function calls:
XPush.XPush.HitTag("TestTag");
XPush.XPush.HitEvent("TestEvent");
  • If you want to receive notifications when your app is in the foreground. This is possible on iOS 10 and above by calling the following method inside FinishedLaunching():
XP.XPush.RegisterForegroundNotificationOptions((XPMessage arg0) =>
{
    ///you can return different foreground options based on particular message.
    ///for example you might want to show notification in foreground only for messages from specific campaign id
    if (arg0.CampaignIdentifier == "travel") 
    {
        return XP.XPNotificationType.Alert | XP.XPNotificationType.Badge | XP.XPNotificationType.Sound;
    }

    return XPNotificationType.None;
});

👍

Make sure you set the user ID

It is recommended that at this stage you use our SDK method to set user IDs by following our dedicated guide to ensure devices can be associated and targeted in your campaigns by your own unique identifier.

Troubleshooting

Build error "Could not AOT the assembly ... xpios.dll"

  • Switch off Project Options > Build > iOS Build > Enable incremental builds
  • Rebuild the project again (it should now succeed)
  • It should be possible to enable incremental builds again after this point