AWS Mobile
Developer Guide

Add Push Notifications to Your Mobile App with Amazon Pinpoint


Mobile Hub deploys your Push Notifications backend services when you enable the Messaging and Analytics feature using the Amazon Pinpoint service. Amazon Pinpoint enables apps to receive mobile push messages sent from the Apple (APNs) and Google (FCM/GCM) platforms. You can also create Amazon Pinpoint campaigns that tie user behavior to push or other forms of messaging.

Set Up Your Backend

  1. Complete the Get Started steps before your proceed.

  2. Choose the Messaging and Analytics tile

  3. Choose Mobile push.

    For Android - Firebase/Google Cloud Messaging (FCM/GCM): Choose Android and provide your Firebase/Google application API key and Sender ID. To retrieve or create these values, see Setting Up Android Push Notifications .

    For iOS - Apple Push Notification Service (APNs): Choose iOS and provide your Apple app P12 Certificate and, optionally, Certificate password. To retrieve or create these items, see Setting Up iOS Push Notifications.

  4. When the operation is complete, an alert will pop up saying "Your Backend has been updated", prompting you to download the latest copy of the cloud configuration file. If you're done with configuring the feature, choose the banner to return to the project details page.

  5. From the project detail page, every app that needs to be updated with the latest cloud configuration file will have a flashing Integrate button. Choose the button to enter the integrate wizard.

  6. Update your app with the latest copy of the cloud configuration file. Your app now references the latest version of your backend. Choose Next and follow the Push Notification documentation below to connect to your backend.

Connect to your backend

To add push notification to your app

Android - JavaiOS - Swift
Android - Java
  1. Set up AWS Mobile SDK components with the following Set Up Your Backend steps.

    1. AndroidManifest.xml must contain:

      <uses-permission android:name="android.permission.WAKE_LOCK"/> <uses-permission android:name="" /> <permission android:name="com.mysampleapp.permission.C2D_MESSAGE" android:protectionLevel="signature" /> <uses-permission android:name="com.mysampleapp.permission.C2D_MESSAGE" /> <application <!--Add these to your Application declaration to filter for the notification intent--> <receiver android:name="" android:exported="true" android:permission="" > <intent-filter> <action android:name="" /> <category android:name="com.mysampleapp" /> </intent-filter> </receiver> <service android:name=".PushListenerService" android:exported="false" > <intent-filter> <action android:name="" /> </intent-filter> </service> </application>
    2. Add the following to your app/build.gradle:

      dependencies{ compile 'com.amazonaws:aws-android-sdk-pinpoint:2.6.+' compile ('com.amazonaws:aws-android-sdk-auth-core:2.6.+@aar') {transitive = true;} compile '' compile '' }
    3. Add the following to your project level build.gradle:

      buildscript { dependencies { classpath '' } } allprojects { repositories { maven { url "" } } }
  2. Create an Amazon Pinpoint client in the location of your push notification code.

    import com.amazonaws.mobileconnectors.pinpoint.PinpointConfiguration; import com.amazonaws.mobileconnectors.pinpoint.PinpointManager; import; import; public class MainActivity extends AppCompatActivity { public static final String LOG_TAG = MainActivity.class.getSimpleName(); public static PinpointManager pinpointManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (pinpointManager == null) { PinpointConfiguration pinpointConfig = new PinpointConfiguration( getApplicationContext(), AWSMobileClient.getInstance().getCredentialsProvider(), AWSMobileClient.getInstance().getConfiguration()); pinpointManager = new PinpointManager(pinpointConfig); new Thread(new Runnable() { @Override public void run() { try { String deviceToken = InstanceID.getInstance(MainActivity.this).getToken( "123456789Your_GCM_Sender_Id", GoogleCloudMessaging.INSTANCE_ID_SCOPE); Log.e("NotError", deviceToken); pinpointManager.getNotificationClient() .registerGCMDeviceToken(deviceToken); } catch (Exception e) { e.printStackTrace(); } } }).start(); } } }
iOS - Swift
  1. Set up AWS Mobile SDK components with the following Set Up Your Backend steps.

    1. Podfile that you configure to install the AWS Mobile SDK must contain:

      platform :ios, '9.0' target :'YOUR-APP-NAME' do use_frameworks! pod 'AWSPinpoint', '~> 2.6.13' # other pods end

      Run pod install --repo-update before you continue.

    2. Classes that call Amazon Pinpoint APIs must use the following import statements:

      import AWSCore import AWSPinpoint
  2. Create an Amazon Pinpoint client by using the following code into the didFinishLaunchwithOptions method of your app's AppDelegate.swift. This will also register your device token with Amazon Pinpoint.

    var pinpoint: AWSPinpoint? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { pinpoint = AWSPinpoint(configuration: AWSPinpointConfiguration.defaultPinpointConfiguration(launchOptions: launchOptions)) return true }

Add Amazon Pinpoint Targeted and Campaign Push Messaging

Amazon Pinpoint console enables you to target your app users with push messaging. You can send individual messages or configure campaigns that target a group of users that match a profile that you define. For instance, you could email users that have not used the app in 30 days, or send an SMS to those that frequently use a given feature of your app.

Android - JavaiOS - Swift
Android - Java

The following 2 steps show how to receive push notifications targeted for your app.

  1. Add a Push Listener Service to Your App.

    The name of the class must match the push listener service name used in the app manifest. pinpointManager is a reference to the static PinpointManager variable declared in the MainActivity shown in a previous step. Use the following steps to set up Push Notification listening in your app.

    1. The following push listener code assumes that the app's MainActivity is configured using the manifest setup described in a previous section.

      import android.content.Intent; import android.os.Bundle; import; import android.util.Log; import com.amazonaws.mobileconnectors.pinpoint.targeting.notification.NotificationClient; import; public class YOUR-PUSH-LISTENER-SERVICE-NAME extends GcmListenerService { public static final String LOGTAG = PushListenerService.class.getSimpleName(); // Intent action used in local broadcast public static final String ACTION_PUSH_NOTIFICATION = "push-notification"; // Intent keys public static final String INTENT_SNS_NOTIFICATION_FROM = "from"; public static final String INTENT_SNS_NOTIFICATION_DATA = "data"; /** * Helper method to extract push message from bundle. * * @param data bundle * @return message string from push notification */ public static String getMessage(Bundle data) { // If a push notification is sent as plain // text, then the message appears in "default". // Otherwise it's in the "message" for JSON format. return data.containsKey("default") ? data.getString("default") : data.getString( "message", ""); } private void broadcast(final String from, final Bundle data) { Intent intent = new Intent(ACTION_PUSH_NOTIFICATION); intent.putExtra(INTENT_SNS_NOTIFICATION_FROM, from); intent.putExtra(INTENT_SNS_NOTIFICATION_DATA, data); LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } @Override public void onMessageReceived(final String from, final Bundle data) { Log.d(LOGTAG, "From:" + from); Log.d(LOGTAG, "Data:" + data.toString()); final NotificationClient notificationClient = MainActivity.pinpointManager.getNotificationClient(); NotificationClient.CampaignPushResult pushResult = notificationClient.handleGCMCampaignPush(from, data, this.getClass()); if (!NotificationClient.CampaignPushResult.NOT_HANDLED.equals(pushResult)) { // The push message was due to a Pinpoint campaign. // If the app was in the background, a local notification was added // in the notification center. If the app was in the foreground, an // event was recorded indicating the app was in the foreground, // for the demo, we will broadcast the notification to let the main // activity display it in a dialog. if ( NotificationClient.CampaignPushResult.APP_IN_FOREGROUND.equals(pushResult)) { // Create a message that will display the raw //data of the campaign push in a dialog. data.putString(" message", String.format("Received Campaign Push:\n%s", data.toString())); broadcast(from, data); } return; } } }
    2. Add code to react to your push listener service.

      The following code can be placed where your app will react to incoming notifications.

      import; import; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import; import; import android.os.Bundle; import android.util.Log; public class MainActivity extends AppCompatActivity { public static final String LOG_TAG = MainActivity.class.getSimpleName(); @Override protected void onPause() { super.onPause(); // unregister notification receiver LocalBroadcastManager.getInstance(this).unregisterReceiver(notificationReceiver); } @Override protected void onResume() { super.onResume(); // register notification receiver LocalBroadcastManager.getInstance(this).registerReceiver(notificationReceiver, new IntentFilter(PushListenerService.ACTION_PUSH_NOTIFICATION)); } private final BroadcastReceiver notificationReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d(LOG_TAG, "Received notification from local broadcast. Display it in a dialog."); Bundle data = intent.getBundleExtra(PushListenerService.INTENT_SNS_NOTIFICATION_DATA); String message = PushListenerService.getMessage(data); new AlertDialog.Builder(MainActivity.this) .setTitle("Push notification") .setMessage(message) .setPositiveButton(android.R.string.ok, null) .show(); } }; }
iOS - Swift
  1. In your AppDelegate with PinpointManager instantiated, make sure the push listening code exists in the following functions.

    // . . . func application( _ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { pinpoint!.notificationManager.interceptDidRegisterForRemoteNotifications( withDeviceToken: deviceToken) } func application( _ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { pinpoint!.notificationManager.interceptDidReceiveRemoteNotification( userInfo, fetchCompletionHandler: completionHandler) if (application.applicationState == .active) { let alert = UIAlertController(title: "Notification Received", message: userInfo.description, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) UIApplication.shared.keyWindow?.rootViewController?.present( alert, animated: true, completion:nil) } } // . . . }
  2. Add the following code in the ViewController where you request notification permissions.

    var userNotificationTypes : UIUserNotificationType userNotificationTypes = [.alert , .badge , .sound] let notificationSettings = UIUserNotificationSettings.init(types: userNotificationTypes, categories: nil) UIApplication.shared.registerUserNotificationSettings(notificationSettings) UIApplication.shared.registerForRemoteNotifications()
  3. In Xcode, choose your app target in the Project Navigator, choose Capabilities, turn on Push Notifications.

                           Image of turning on Push Notifications capabilities in Xcode.
  4. Build and run your app using information at Building the Sample iOS App From AWS Mobile Hub.