Xamarin Android Setup


Send push notifications to your Xamarin.Android app with Pushy.

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

Create an App

Note: No credit card needed. Upgrade to the Pro plan when you're ready by setting up Billing.


Note: If you have already created an app in the Pushy Dashboard for another platform, simply configure your existing app with your Android Package Name & iOS Bundle ID in the App Settings tab and proceed to the next step.

Click Create and proceed to the next step.

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">
    <intent-filter>
        <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
    </intent-filter>
</receiver>

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

<!-- Pushy Socket Service -->
<!-- Do not modify - internal service -->
<service android:name="me.pushy.sdk.services.PushySocketService" android:stopWithTask="false" />

<!-- Pushy Job Service (added in Pushy SDK 1.0.35) -->
<!-- Do not modify - internal service -->
<service android:name="me.pushy.sdk.services.PushyJobService"
    android:permission="android.permission.BIND_JOB_SERVICE"
    android:stopWithTask="false" />

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

Users need to be uniquely identified to receive push notifications.

Every user is assigned a unique device token that you can use to push it at any given time. Once the user has been assigned a device token, it should be stored in your application's backend database.


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

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 user for notifications:

await RegisterForPushNotifications();

Copy the following RegisterForPushNotifications() method implementation and modify it accordingly to send device tokens to your backend server.

private async Task RegisterForPushNotifications()
{
    // Execute Pushy.Register() in a background thread
    await Task.Run(() =>
    {
        try
        {
            // 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);
            return;
        }

        // Succeeded, optionally 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.

Find:
base.OnCreate(savedInstanceState);
Add Below:
Pushy.Listen(this);
Android 6.0+ Compatibility

Skip this if your targetSdkVersion is less than 23.

Android 6.0 and up requires apps with a targetSdkVersion >= 23 to explicitly request certain permissions from users via permission dialogs. Since Pushy persists device tokens in the external storage (to persist data between app reinstallations), please request external storage access from your users.

Find:
Pushy.Listen(this);
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;
using ME.Pushy.Sdk;

namespace MyApp
{
	[BroadcastReceiver(Enabled = true, Exported = false)]
	[IntentFilter(new[] { "pushy.me" })]
	public class PushReceiver : BroadcastReceiver
	{
		public override void OnReceive(Context context, Intent intent)
		{
			string notificationTitle = "MyApp";
			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)
				  .SetAutoCancel(true)
				  .SetSmallIcon(Android.Resource.Drawable.IcDialogInfo)
				  .SetContentTitle(notificationTitle)
				  .SetContentText(notificationText)
				  .SetLights(Color.Red, 1000, 1000)
				  .SetVibrate(new long[] { 0, 400, 250, 400 })
				  .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification))
				  .SetContentIntent(PendingIntent.GetActivity(context, 0, new Intent(context, typeof(MainActivity)), PendingIntentFlags.UpdateCurrent));

			// Automatically configure a Notification Channel for devices running Android O+
			Pushy.SetNotificationChannel(builder, context);
                
			// 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 payload:

{"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

Optionally subscribe the user to one or more topics to target multiple users 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 users. If your app only sends personalized notifications, skip this step and simply target individual users by their unique device tokens.


Simply add the following blocking code to subscribe the user 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 multiple users 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.

Did you receive the notification? If not, reach out, we'll be glad to help.


Congratulations on implementing Pushy in your Xamarin.Android app!

To start sending push notifications to your users, start persisting device tokens in your backend, and invoke the Send Notifications API when you want to send a notification. Follow our step-by-step guide: