Xamarin Android Setup

To start sending push notifications to your Xamarin.Android app with Pushy, you'll need to make a few changes to your application.

At any time, you may refer to our Xamarin.Android demo project for a working demo.

Get the SDK

Install the SDK by searching for Pushy within your project's NuGet package manager:

Note: Make sure the Id of the package you are installing is Pushy.SDK.Xamarin.Android.

Modify AndroidManifest

Add the following lines to your AndroidManifest.xml, inside the <manifest> tag:

<!-- Pushy Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<!-- End Pushy Permissions -->

You should manually omit any permission declarations that your app already asks for.

Note: android.permission.WRITE_EXTERNAL_STORAGE is optional - it is necessary only for persisting device tokens in the external storage for when your app is reinstalled, so we don't charge you twice for the same device. If this permission is not declared, the SDK will persist device tokens only within your app's SharedPreferences, which are cleared when your app is uninstalled.

Add the following lines to your AndroidManifest.xml, inside the <application> tag:

<!-- Pushy Declarations -->

<!-- Pushy Update Receiver -->
<!-- Do not modify - internal BroadcastReceiver that restarts the listener service -->
<receiver android:name="me.pushy.sdk.receivers.PushyUpdateReceiver" android:exported="false">
        <action android:name="android.intent.action.PACKAGE_REPLACED" />
        <data android:scheme="package" />

<!-- Pushy Boot Receiver -->
<!-- Do not modify - internal BroadcastReceiver that restarts the listener service -->
<receiver android:name="me.pushy.sdk.receivers.PushyBootReceiver" android:exported="false">
        <action android:name="android.intent.action.BOOT_COMPLETED"/>

<!-- Pushy Socket Service -->
<!-- Do not modify - internal socket service -->
<service android:name=""/>

<!-- End Pushy Declarations -->
Register Devices

Devices need to be uniquely identified to receive push notifications.

Every device is assigned a unique token that you can use to push it at any given time. Once the device has been assigned a token, it should be stored in your application's backend database. When you're ready to push the device, your backend server will send its token to our REST API, and we'll deliver the push notification to the corresponding device.

Simply add the following blocking code to your application when you're ready to register the device:

var deviceToken = Pushy.Register(Application.Context);

Note: Pushy.Register(Context) is a synchronous, blocking call, so make sure to only execute it from within a background thread.

Asynchronous Implementation

Add the following code to your application when you're ready to register the device:

await RegisterForPushNotifications();

Copy the following RegisterForPushNotifications() method implementation and modify it accordingly to send device tokens to your backend server. You can skip the backend implementation for now, we'll get to that later.

private async Task RegisterForPushNotifications()
    // Execute Pushy.Register() in a background thread
    await Task.Run(() =>
            // Assign a unique token to this device
            string deviceToken = Pushy.Register(this);

            // Log it for debugging purposes
            Log.Debug("MyApp", "Pushy device token: " + deviceToken);

            // Send the token to your backend server via an HTTP GET request
            new URL("https://{YOUR_API_HOSTNAME}/register/device?token=" + deviceToken).OpenConnection();
        catch (Exception exc)
            // Log error to console
            Log.Error("MyApp", exc.Message, exc);

        // Succeeded, do something to alert the user
Modify Launcher Activity

Invoke Pushy.listen(this) in your launcher activity's OnCreate() method so that Pushy's internal notification listening service will restart itself, if necessary.

Add Below:
Android 6.0+ Compatibility

Skip this if your targetSdkLevel is less than 23.

Android 6.0 and newer versions require apps with a targetSdkLevel >= 23 to explicitly request permissions from users via permission dialogs. Since Pushy persists device tokens in the external storage (to survive app reinstallation), you must add the following code to your app's launcher activity.

Add Below:
// Check whether the user has granted us the READ/WRITE_EXTERNAL_STORAGE permissions
if (ContextCompat.CheckSelfPermission(Application.Context, Manifest.Permission.WriteExternalStorage) != Permission.Granted)
    // Request both READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE so that the
    // Pushy SDK will be able to persist the device token in the external storage
    ActivityCompat.RequestPermissions(this, new string[] { Manifest.Permission.ReadExternalStorage, Manifest.Permission.WriteExternalStorage }, 0);
Setup BroadcastReceiver

Declare a BroadcastReceiver that will receive your push notifications when they arrive. Your app can then execute any relevant action in response, such as displaying a notification, playing a sound, making a request, etc.

Create a PushReceiver.cs file within your app with the following sample code that displays a notification when a push is received:

using Android.App;
using Android.Content;
using Android.Graphics;
using Android.Media;
using Android.Support.V7.App;

namespace MyApp
	[BroadcastReceiver(Enabled = true, Exported = false)]
	[IntentFilter(new[] { "" })]
	public class PushReceiver : BroadcastReceiver
		public override void OnReceive(Context context, Intent intent)
			string notificationTitle = "Pushy";
			string notificationText = "Test notification";

			// Attempt to extract the "message" property from the payload: {"message":"Hello World!"}
			if (intent.GetStringExtra("message") != null)
				notificationText = intent.GetStringExtra("message");

			// Prepare a notification with vibration, sound and lights
			var builder = new NotificationCompat.Builder(context)
				  .SetLights(Color.Red, 1000, 1000)
				  .SetVibrate(new long[] { 0, 400, 250, 400 })
				  .SetContentIntent(PendingIntent.GetActivity(context, 0, new Intent(context, typeof(MainActivity)), PendingIntentFlags.UpdateCurrent));

			// Get an instance of the NotificationManager service
			var notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService);

			// Build the notification and display it
			notificationManager.Notify(1, builder.Build());

Make sure to replace the MyApp namespace with your project namespace, and MainActivity with the name of your main activity.

Note: Please make sure to request the android.permission.VIBRATE permission within your AndroidManifest.xml if you'd like the notification to vibrate the device.

Feel free to modify this sample code to suit your own needs. In the next step, we'll take a look at how to parse the incoming payload data sent by your backend server.

Parse Notification Data

Any payload data that you send with your push notifications is made available to your app via the Intent extras of your PushReceiver class.

If you were to send a push notification with the following data:

{"id": 1, "success": true, "message": "Hello World"}

Then you'd be able to retrieve each value from within your PushReceiver.cs file like so:

int id = intent.GetIntExtra("id", 0);
string message = intent.GetStringExtra("message");
bool success = intent.GetBooleanExtra("success", false);

Note: Unlike GCM / FCM, we do not stringify your payload data, except if you supply JSON objects or arrays. This means that if you send {"id": 3}, you'd retrieve that value in the receiver using intent.GetIntExtra("id", 0).

Subscribe to Topics (Optional)

Optionally subscribe the device to one or more topics to target multiple devices with a shared interest when sending notifications.

Depending on your app's notification criteria, you may be able to leverage topics to simply the process of sending the same notification to multiple devices. If your app only sends personalized notifications, skip this step and simply target individual devices by specifying their tokens.

Simply add the following blocking code to subscribe a registered device to a topic:

Pushy.Subscribe("news", Application.Context);

Note: Make sure to execute this method from a background thread, similar to Pushy.Register(Context).

Also, replace news with your own case-sensitive topic name that matches the following regular expression: [a-zA-Z0-9-_.]+. You may also pass in a string[] array with multiple topics.

You can then notify devices subscribed to a certain topic by specifying the topic name (prefixed with /topics/) as the to parameter in the Send Notifications API.

Send Test Notification

Input your device token and select your app to send a test push notification:

Note: You can specify a topic instead of a device token (i.e. /topics/news). Also, if your app is not automatically detected, please manually copy the Secret API Key from the Dashboard and paste it into the form.

Check if your device received the notification. Did it work? If not, contact us, we'll help you out.

Integration Complete

Congratulations on implementing Pushy in your app!

Now, all that's left is to setup your backend. Head on over to the Backend Setup guide to begin persisting device tokens as well as implementing the logic for sending push notifications to your app.