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.

ūüĎć

To integrate successfully 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. You will find links to documentation on connecting to the platform below:

A full Xamarin integration guide is given for Android and iOS below. Note 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

  • Follow the steps under Get configuration values in the Android push notifications guide, to save your google-services.json file associated with your project.
  • 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 71.1600.0)
    • Xamarin.Firebase.Messaging (latest stable NuGet package currently 71.1740.0)
  • Edit the AndroidManifest.xml file to add the following elements within the manifest element.
<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <permission android:name=".permission.C2D_MESSAGE" android:protectionLevel="signature" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <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" />
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
  • 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="ie.imobile.extremepush.ui.temptask" />
        <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">
            <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="true" />
        <receiver android:name="ie.imobile.extremepush.location.GeoLocationBroadcastReceiver" android:exported="true" />
        <receiver android:name="ie.imobile.extremepush.location.ProxymityAlertReceiver" android:exported="true" />
        <receiver android:name="ie.imobile.extremepush.receivers.XP_App_Update_Receiver">
            <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">
            <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¬†NSLocationAlwaysUsageDescription,¬†NSLocationAlwaysAndWhenInUseUsageDescription 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;
});

Troubleshooting

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

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

Updated 7 months ago


Xamarin


Add Xtremepush to both iOS and Android apps built with Xamarin

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.