Configure and activate devices

To push notifications with Ably, you must first configure the device using its platform-specific notification service (APNs for iOS or FCM for Android) and integrate it with Ably’s infrastructure. You can then activate the push notifications service, either directly or via a server.

Configuration is the first step in setting up push notifications with Ably. This step requires setting up the necessary infrastructure on the device’s operating system or platform, such as iOS with APNs or Android with FCM, as well as on the Ably platform.

Push Notifications in Ably

  • Go to the Firebase Console.
  • Click add project and follow the steps to create and manage service account keys.
  • Download your service account JSON file.
  • In your Ably dashboard, navigate to the Notifications tab under your app settings.
  • Go to push notifications setup, click configure push.
  • Add your service account JSON file to the setting up Firebase cloud messaging section.
  • Go to the Apple Developer Program.
  • Use the Apple developer portal to create a push notification service certificate for your app.
  • Export the certificate as a .p12 file.
  • Next, you can either import the .p12 cert or create a PEM file and copy it into your Ably dashboard:
  • Import the .p12 file:
    • In your Ably dashboard, navigate to the Notifications tab under your app settings.
    • Go to push notifications setup, click configure push and scroll to the setting up Apple push notification service section.
    • Select the .p12 file you exported and enter the password you created during the export process.
    • Click save. You should receive confirmation that the certificate has been successfully imported.
    • To further confirm the import, refresh the page and check if the PEM cert and private key text boxes are now populated with the imported key details.
  • Create a PEM file from the .p12 file:
    • Using OpenSSL, convert the recently exported .p12 file (io.ably.test.p12) to a PEM file with the following command: $ openssl pkcs12 -in ./io.ably.test.p12 -out ./io.ably.test.pem -nodes -clcerts.
    • Open the PEM file in your text editor.
    • Copy everything between and including -----BEGIN CERTIFICATE----- and -----END CERTIFICATE-----, and paste it into the PEM cert text box of the Apple push notification service section of your Ably notifications app dashboard.
    • Similarly, copy everything between and including -----BEGIN PRIVATE KEY----- and -----END PRIVATE KEY-----, and paste it into the PEM private key text box of the same section. Then, click save.

Use the following code to install and set up your Ably SDK:

Select...
// Add the Ably SDK into your build.gradle dependencies and ensure there's a reference to Maven in the repositories section: dependencies { implementation 'io.ably:ably-android:1.2.0' } repositories { mavenCentral() }
Copied!

To receive push notifications using Ably, each device must first register with the platform-specific push notification service — APNs and FCM, or for web push, the service worker registration’s push manager. Ably’s SDK facilitates this registration process and provides a unified API to manage it across different platforms.

Push Notifications in Ably

Activating a device for push notifications is typically done directly on the device itself. Use the push.activate() method to activate push notifications from a device. The following steps describe the direct activation process:

  1. Authenticate the Ably client.
  2. Generate a unique identifier for the device and saves it locally.
  3. Activate push notifications for the device with the underlying OS, obtaining a unique identifier like a registration token for FCM or a device token for APNs.
  4. Register the device with Ably, providing its unique identifier (deviceId), platform details, and push recipient information.
  5. Store the device’s identity token from Ably’s response locally for authentication in subsequent updates.

Note that once activated, the device remains registered even after the application is closed until the push.deactivate() method is called. Calling activate again has no effect if the device is already activated.

The following diagram demonstrates the direct activation process:

push notifications in Ably

The following example initializes an instance of the Ably Realtime service and then activates the push notifications feature for that instance:

Select...
val ably = getAblyRealtime() ably.setAndroidContext(context) ably.push.activate()
Copied!

Test your push notification activation

  • Use the Ably dashboard or API to send a test push notification to a registered device.
  • Ensure your application correctly receives and handles the push notification.

In specific scenarios, especially where strict control over device capabilities is essential, managing the activation of devices for push notifications through the server is useful. This approach separates the registration with the device’s platform-specific push notification service, which still happens on the device. Meanwhile, your server manages the device registration with Ably. This setup provides a centralized and efficient process for controlling devices.

The following steps explain the server assisted activation process:

  1. The device initiates the activation process by registering with its respective platform service (APNs or FCM) to obtain a unique device identifier, such as a registration token or device token.
  2. Instead of registering itself with Ably, the device sends its platform-specific identifier to your server. Your server then uses this identifier to register the device with Ably using Ably’s Push Admin API.
  3. The server stores and manages the device tokens. It is responsible for updating these tokens in Ably’s system whenever they change, which can be triggered by the device sending a new token to the server following the platform service’s renewal.

The following diagram demonstrates the process for activating devices from a server:

push notifications in Ably

Activate Android devices via server

Your application must interact with the Ably SDK to configure server-side registration for push notifications, utilizing the LocalBroadcastManager for communication.

Ensure that the useCustomRegisterer parameter is set to true when calling push.activate() or push.deactivate().

Select...
ably.push.activate(context, true) ably.push.deactivate(context, true)
Copied!

Upon activation or deactivation, the Ably SDK broadcasts signals indicating whether to register or deregister the device from your server. It uses io.ably.broadcast.PUSH_REGISTER_DEVICE for registration and io.ably.broadcast.PUSH_DEREGISTER_DEVICE for deregistration. To handle these broadcasts, implement a listener in your app’s AndroidManifest.xml and respond by sending back PUSH_DEVICE_REGISTERED or PUSH_DEVICE_DEREGISTERED as appropriate.

The following examples set up the server-side activation:

<receiver android:name=".MyAblyBroadcastReceiver"> <intent-filter> <action android:name="io.ably.broadcast.PUSH_REGISTER_DEVICE" /> <action android:name="io.ably.broadcast.PUSH_DEREGISTER_DEVICE" /> <intent-filter> <receiver>
Copied!
Select...
class MyAblyBroadcastReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val ably = getAblyRealtime() val action = intent.action when (action) { "io.ably.broadcast.PUSH_REGISTER_DEVICE" -> { val device = ably.device(context) val isNew = intent.getBooleanExtra("isNew", false) val response = Intent("io.ably.broadcast.PUSH_DEVICE_REGISTERED") try { val deviceIdentityToken: String = registerThroughYourServer(device, isNew) response.putExtra("deviceIdentityToken", deviceIdentityToken) } catch (e: AblyException) { IntentUtils.addErrorInfo(intent, e.errorInfo) } LocalBroadcastManager.getInstance(context.applicationContext).sendBroadcast(response) } "io.ably.broadcast.PUSH_DEREGISTER_DEVICE" -> { val device = ably.device(context) try { deregisterThroughYourServer(device.id) } catch (e: AblyException) { IntentUtils.addErrorInfo(intent, e.errorInfo) } LocalBroadcastManager.getInstance(context.applicationContext).sendBroadcast(intent) } } } }
Copied!

Activate iOS device via server

When setting up server-side registration for push notifications on iOS, your application must interact with the Ably SDK to handle device registration and deregistration securely and effectively. Implement the following optional methods from ARTPushRegistererDelegate in your UIApplicationDelegate to customize the registration process:

Select...
func ablyPushCustomRegister(_ error: ARTErrorInfo?, deviceDetails: ARTDeviceDetails, callback: @escaping (ARTDeviceIdentityTokenDetails?, ARTErrorInfo?) -> Void) { if let e = error { // Log or handle the error as needed callback(nil, e) return } // Your server-side logic to register the device self.registerThroughYourServer(deviceDetails: deviceDetails, callback: callback) } func ablypushCustomDeregister(_ error: ARTErrorInfo?, deviceId: String, callback: @escaping (ARTErrorInfo?) -> Void) { if let e = error { // Log or handle the error as needed callback(nil, e) return } // Your server-side logic to deregister the device self.unregisterThroughYourServer(deviceId: deviceId, callback: callback) }
Copied!

Activate Android and iOS devices via server using .NET

Initialize the specific mobile device. You can achieve this by using either AppleMobileDevice.Initialize or AndroidMobileDevice.Initialize. To initialize, you need to pass a valid Ably.ClientOptions, which will be used to initialize the Ably realtime client, and an instance of PushCallbacks, which you can use to receive notifications when the device is activated, deactivated, or when sync registration fails.

The Initialize method will create an instance of IRealtimeClient, which can be used to activate push notifications for the device by calling client.Push.Activate(). Activation is not guaranteed to happen immediately. The developer will be notified through the ActivatedCallback, which was passed to the Initialize method when setting up push notifications.

Select...
public override bool FinishedLaunching(UIApplication app, NSDictionary options) { Xamarin.Forms.Forms.Init(); InitialiseAbly(); //... return base.FinishedLaunching(app, options); } private void InitialiseAbly() { var clientId = ""; // Set or generate a clientId. Use the clientId to send push notifications to a device. var callbacks = new PushCallbacks { ActivatedCallback = error => { /* handle notification */ }, DeactivatedCallback = error => { /* handle notification */ }, SyncRegistrationFailedCallback = error => { /* handle notification */ }, }; // IOS _realtime = AppleMobileDevice.Initialise(GetAblyOptions(clientId), callbacks); // ANDROID _realtime = AndroidMobileDevice.Initialise(GetAblyOptions(clientId), callbacks); _realtime.Connect(); } private ClientOptions GetAblyOptions(string clientId) { var options = new ClientOptions { Key = "<loading API key, please wait>", ClientId = string.IsNullOrWhiteSpace(clientId) ? Guid.NewGuid().ToString("D") : clientId, }; _realtime = new AblyRealtime(options); // If you are going to use the AblyRealtime client in the app feel free to call Connect here // If not then skip it and add `AutoConnect = false,` to the ClientOptions. _realtime.Connect(); return options; }
Demo Only
Copied!

Test your push notification activation

  • Use the Ably dashboard or API to send a test push notification to a registered device.
  • Ensure your application correctly receives and handles the push notification.

When the push.activate() and push.deactivate() methods are called, the device registers with FCM or APNs. In addition, whenever there is an update to the push token (either the APNs device token or the FCM registration token), the Ably SDK attempts to update this token on Ably’s servers.

Android
  • Handle the push activation: io.ably.broadcast.PUSH_ACTIVATE in a broadcast intent.
  • Handle the push deactivation: io.ably.broadcast.PUSH_DEACTIVATE in a broadcast intent.
  • Handle push registration failure: io.ably.broadcast.PUSH_UPDATE_FAILED in a broadcast intent.
Swift
  • Handle the push activation func didActivateAblyPush(_ error: ARTErrorInfo?)
  • Handle the push deactivation func didDeactivateAblyPush(_ error: ARTErrorInfo?)
  • Handle push registration failure func didAblyPushRegistrationFail(_ error: ARTErrorInfo?)
ObjC
  • Handle the push activation: (void)didActivateAblyPush:(nullable ARTErrorInfo *)error;
  • To the handle push deactivation: (void)didDeactivateAblyPush:(nullable ARTErrorInfo *)error;
  • Handle push registration failure: (void)didAblyPushRegistrationFail:(nullable ARTErrorInfo *)error;=:ionFail:(nullable ARTErrorInfo *)error;
JavaScript
  • For activation, pass a registerCallback to the push.activate method
  • For deactivation, pass a deregisterCallback to the push.deactivate method
  • For failed updates, pass a updateFailedCallback as the second argument to the push.activate method
.NET
  • Handle the push activation: private void HandlePushActivation(ARTErrorInfo error)
  • Handle the push deactivation: private void HandlePushDeactivation(ARTErrorInfo error)
  • Handle push registration failure: (void)didAblyPushRegistrationFail:(nullable ARTErrorInfo *)error;=:ionFail:(nullable ARTErrorInfo *)error;
Configure devices
v2.0