Ready to send your first notification? We'll get you registered so you can start sending notifications faster than a collision-free hash table lookup (OK, maybe not that fast).
A Notifications application involves two components:
The aim of this guide is to show you how to store the app's unique address in Notify by creating a Binding so that later we can send notifications to it. There are two cases when you would need to update the Binding in Notify:
As both acquiring the address of the app and creating a binding may take a bit, it is best to implement registration in a dedicated service (e.g., RegistrationIntentService) and fire it in both scenarios. Let's start with the first scenario, logging a new user in and then adding support for changing addresses.
When a user logs in, you want to capture the Identity and fire the RegistrationIntentService passing the new Identity as an Extra. Let's take a look at then how this RegistrationIntentService works.
First, the RegistrationIntentService needs to acquire the address of the app, and the registration token. This is done by invoking the FirebaseInstanceId.getInstance().getToken(); method.
1public class RegistrationIntentService extends IntentService {2@Override3protected void onHandleIntent(Intent intent) {4String token = FirebaseInstanceId.getInstance().getToken();5}6}
Next, we need to get the Identity from the extra and create a Binding in Twilio. A "Binding" represents a unique app installation that can receive a notification. It associates a registration token (that we just acquired) with an Identity (from the Intent Extra). You can use the Identity to send notifications to a specific user (Identity). (More on that later.)
The app should send a request to the server containing the registration token, Identity, and BindingType. The server then will use this information to create the Binding via the Twilio API. We add this indirection to avoid exposing our Twilio credentials in the Android app.
1public class RegistrationIntentService extends IntentService {2private BindingResource bindingResource;34@Override5protected void onHandleIntent(Intent intent) {6String token = FirebaseInstanceId.getInstance().getToken();7String identity = intent.getStringExtra(IDENTITY);8String storedIdentity = sharedPreferences.getString(IDENTITY, null);9if (newIdentity == null) {10// If no identity was provided to us then we use the identity stored in shared preferences.11// This can occur when the registration token changes.12identity = storedIdentity;13} else {14// Otherwise we save the new identity in the shared preferences for future use.15sharedPreferences.edit().putString(IDENTITY, binding.identity).commit();16}17sendRegistrationToServer(identity, token);18}1920@Override21public void onCreate(){22super.onCreate();23Retrofit retrofit = new Retrofit.Builder()24.baseUrl(AppConstants.BASE_URL).addConverterFactory(JacksonConverterFactory.create(new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL)))25.build();26bindingResource = retrofit.create(BindingResource.class);27}2829private CreateBindingResponse sendRegistrationToServer(String identity, String token) throws IOException {30String endpoint = sharedPreferences.getString(ENDPOINT + newIdentity, null);31Binding binding = new Binding(identity, endpoint, token, "fcm");32Call<CreateBindingResponse> call = bindingResource.createBinding(binding);33Response<CreateBindingResponse> response = call.execute();34sharedPreferences.edit().putString(ENDPOINT + binding.identity, response.body().endpoint).commit();35}36}37
We use retrofit2 to make this request, but you can use any HTTP client. Our mini-API to communicate with our server is defined in the BindingResource, Binding and CreateBindingResponse classes. The BindingResource interface defines the signature of our API.
1public interface BindingResource {2@POST("/register")3Call<CreateBindingResponse> createBinding(@Body Binding binding);4}5
The Binding class is a Plain Old Java Object (POJO) that the retrofit2 API will translate to JSON for us. It wraps the parameters we need to send to the server.
1public class Binding {2public String identity;3public String endpoint;4public String Address;5public String BindingType;67public Binding(String identity, String endpoint, String address, String bindingType) {8this.identity = identity;9this.endpoint = endpoint;10Address = address;11BindingType = bindingType;12}13}14
The CreateBindingResponse is another POJO to translate the server's JSON response including the generated endpoint identifier and a message in case something went wrong.
1package com.twilio.notify.quickstart.notifyapi.model;23/**4* Created by vmuller on 4/19/17.5*/6public class CreateBindingResponse {7public String message;8public String endpoint;910public String getMessage() {11return message;12}1314public String getEndpoint() {15return endpoint;16}1718public void setMessage(String message) {19this.message = message;20}2122public void setEndpoint(String endpoint) {23this.endpoint = endpoint;24}25}26
We are almost finished with the Android app. Remember that there was another scenario when we wanted to create a Binding: when FCM changed the registration token. To implement this, we will need two steps:
To register the service, we'll add an intent filter to declare the capabilities of our service, the MyInstanceIDService.
1<service android:name="[.MyInstanceIDService]" android:exported="false">2<intent-filter>3<action android:name="com.google.android.gms.iid.InstanceID"/>4</intent-filter>5</service>
Then we can implement this service. All it does is, invoke our RegistrationIntentService to create a new Binding.
You may wonder, how can we just keep creating Bindings without ever deleting any? The Notify API's deduplication feature allows this. It deletes previous Bindings in the same Notify Service that have the same Address (registration token) or Endpoint. Endpoint
is an auto-generated unique identifier that we receive from the Notify service. Notice how our SendRegistrationToServer method stores this Endpoint in the shared preferences and reuses it in subsequent create Binding requests ensuring that Bindings are not duplicated even when the registration token changes.
Now that we have our Android app ready, let's turn our attention to the server that interacts with the Notify API.
In our server app, we'll receive the POST
request. It will contain the following
four parameters.
name | description |
---|---|
Identity | The Identity to which this Binding belongs. Identity is defined by your application and can have multiple endpoints. |
Endpoint | The identifier of the device to which this registration belongs. Endpoints are also defined by your application. |
BindingType | The type of the Binding determines the transport technology to use. |
Address | The address obtained from the vendor. For APNS it is the device token. For FCM, it is the registration token. |
Notify uses Identity as a unique identifier of a user. You should not use directly identifying information (aka personally identifiable information or PII) like a person's name, home address, email or phone number, etc. as Identity, because the systems that will process this attribute assume it is not directly identifying information.
We'll use index.js in our server app and these four parameters to send an API request to Twilio. Then, we'll send a success message or an error back to the mobile app together with the Endpoint. We implement this logic in the /register endpoint, but this is not required. You can come up with your own API, and perhaps integrate it into a login or a session initialization flow.
1// Download the helper library from https://www.twilio.com/docs/node/install2const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";34// Find your Account SID and Auth Token at twilio.com/console5// and set the environment variables. See http://twil.io/secure6const accountSid = process.env.TWILIO_ACCOUNT_SID;7const authToken = process.env.TWILIO_AUTH_TOKEN;8const client = twilio(accountSid, authToken);910async function createBinding() {11const binding = await client.notify.v112.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")13.bindings.create({14address: "fcm_device_token",15bindingType: "fcm",16endpoint: "XXXXXXXXXXXXXXX",17identity: "00000001",18tag: ["preferred device"],19});2021console.log(binding.sid);22}2324createBinding();
1{2"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",3"address": "fcm_device_token",4"binding_type": "fcm",5"credential_sid": null,6"date_created": "2015-07-30T20:00:00Z",7"date_updated": "2015-07-30T20:00:00Z",8"endpoint": "XXXXXXXXXXXXXXX",9"identity": "00000001",10"notification_protocol_version": "3",11"service_sid": "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",12"sid": "BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",13"tags": [14"26607274"15],16"links": {17"user": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/24987039"18},19"url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings/BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"20}
Now that we've registered the client app with Firebase Cloud Messaging and created a Binding, it's time to send some notifications! Check out our Sending Notifications guide for more information.