Front-End Web & Mobile

AWS Amplify supports Push Notifications for Android, Swift, React Native, and Flutter apps

AWS Amplify is announcing push notifications support for Android, Swift, Flutter, and React Native. Push notifications are an essential component of modern mobile applications. They allow you to keep your users engaged and informed by delivering timely and relevant updates. AWS Amplify’s new push notification support means you can now leverage the power of the cloud to send notifications directly to your users’ devices. One of the most exciting aspects of this new feature is its ease of use. With just a few lines of code, you can integrate push notifications into your app and start sending messages to your users right away. This simplicity means you can focus on what you do best – developing amazing apps – without worrying about the difficult setup.

AWS Amplify integrates with Amazon Pinpoint, allowing you to segment and target your users, and deliver personalized push notifications.

In this blog post, we will show you how to add push notifications features to your Android applications with AWS Amplify, and then send targeted messages to your users.

Pre-requisites

In order to setup Push Notifications with your Android app, you need to add the Amplify libraries, setup your backend resources with the Amplify CLI, and setup a Firebase project.

Create your App and install the Amplify libraries

You can get started with creating a new Android app using Android Studio by following these steps:

  • Open Android Studio.
  • Create a new project, and select “Empty Activity”, press Next.
  • Next, configure your project:
    • Enter MyAmplifyApp in the Name field
    • Select either Java or Kotlin from the Language dropdown menu
    • Select API 24: Android 7.0 (Nougat) from the Minimum SDK dropdown menu
    • Press Finish

Android Studio will open your project with a tab opened to either MainActivity.java or MainActivity.kt depending upon if you created a Java or Kotlin project respectively.

  • Under Gradle Scripts, open build.gradle (Module :app), add the following lines and save the file.
android {
    compileOptions {
        // Support for Java 8 features
        coreLibraryDesugaringEnabled true
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    // Amplify core dependency
    implementation 'com.amplifyframework:core:2.5.0'

    // Support for Java 8 features
    coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'
    implementation 'com.amplifyframework:aws-auth-cognito:2.5.0' 
    implementation 'com.amplifyframework:aws-push-notifications-pinpoint:2.5.0' }
  • Android Studio requires you to sync your project with your new configuration. To do this, click Sync Now in the notification bar above the file editor.
    • When complete, you will see CONFIGURE SUCCESSFUL in the output in the Build tab at the bottom of your screen.
  • Add the following service to your app’s ./app/AndroidManifest.xml file:
<application ...>
  ...
    <service android:name="com.amplifyframework.pushnotifications.pinpoint.FCMPushNotificationService" 
    android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
  ...
</application>
  • Create a file under the .app/java/<com.example.myamplifyapp>/ directory titled Backend.kt
//This import will depend on the name of the Application name you have selected
package com.example.myamplifyapp

import android.app.Application
import android.util.Log
import com.amplifyframework.AmplifyException
import com.amplifyframework.auth.cognito.AWSCognitoAuthPlugin
import com.amplifyframework.core.Amplify
import com.amplifyframework.pushnotifications.pinpoint.AWSPinpointPushNotificationsPlugin

class AndroidGettingStartedApplication : Application() {

    override fun onCreate() {
        super.onCreate()
        try {
            Amplify.addPlugin(AWSCognitoAuthPlugin())
            Amplify.addPlugin(AWSPinpointPushNotificationsPlugin())
            Amplify.configure(applicationContext)
            Log.i(AndroidGettingStartedApplication::class.simpleName, "Initialized Amplify")
        } catch (e: AmplifyException) {
            Log.e(AndroidGettingStartedApplication::class.simpleName, "Could not initialize Amplify", e)
        }
    }
}

Set up Firebase project

You can follow these steps to set up your Firebase project, and retrieve the API key you will connect to Amazon Pinpoint to handle the sending of Push Notifications.

  1. Go to the Firebase console.
  2. In the center of the project overview page, click the Android icon or Add app to launch the setup workflow.
  3. Enter your app’s package name in the Android package name field.
    • Find your app’s package name in your module (app-level) Gradle file, usually app/build.gradle (example package name: com.example.myamplifyapp).
  4. Click Register app.
  5. Download the Firebase Android configuration file (google-services.json), and add it to the module (app-level) root directory of your app.

Next, you will need to access your ServerKey (Referred to as ApiKey in the CLI setup):

  1. Open the Firebase console.
  2. Choose your Firebase project.
  3. Select the gear icon located in the top left hand corner of your screen, then select Project settings.
  4. Select the Cloud Messaging tab.
  5. Select the three vertical dots next to Cloud Messaging API (Legacy), then select Manage API in Google Cloud Console.
  6. In the new tab, select the Enable button.
  7. Return to the previous tab and refresh the page.
  8. Copy the Token next to Server key, we will use this to setup the Amazon Pinpoint resource with the Amplify CLI.

Setup Backend resources

You can now setup the backend resources you need to send targeted push notification campaigns with Amazon Pinpoint.

  • In your terminal, run this command from the root folder of your application to initialize your Amplify app.
amplify init
  • The Amplify CLI will detect these default settings.
? Enter a name for the project `MyAmplifyApp` ? 
Initialize the project with the above configuration? `No` 
? Enter a name for the environment `dev` 
? Choose your default editor: `Android Studio` 
? Choose the type of app that  building `android`
? Where is your Res directory: `app/res/raw/` 
? Select the authentication method you want to use: `AWS profile` 
? Please choose the profile you want to use `default`
  • Upon successfully running amplify init, you will see a configuration file created in ./app/res/raw/ called amplifyconfiguration.json.
  • You can now add the backend resources which uses Amazon Pinpoint with the Amplify CLI. Run the following command in your terminal
amplify add notifications
  • Choose FCM when prompted
? Choose the push notification channel to enable. 
APNS |  Apple Push Notifications 
❯ FCM | » Firebase Push Notifications 
In-App Messaging 
Email 
SMS 
? Provide your pinpoint resource name: `yourPinpointResourceName` 
? Apps need authorization to send analytics events. 
Do you want to allow guests and unauthenticated users to send analytics events? (we recommend you allow this when getting started) (Y/n) 'Y'
amplify push

Upon completion, amplifyconfiguration.json will be updated to reference the newly provisioned backend push notifications resources.

You now have all of your resources and your Android app setup. You are ready to set up campaigns from Amazon Pinpoint to send push notifications to your users.

Running your app

You can now run your app in an emulator, and you should be able to see a message in Android Studio in the logcat tab that says “Initialized Amplify”. You should also be able to see your push notification token in logcat “Registering push notifications token: X”

If both are these messages are shown to you after you run your app, then you have successfully set up your app to receive push notifications!

Setup marketing campaigns and send push notifications

Using Amazon Pinpoint, you can use attributes and metrics to target and segment your users. You can visit this documentation page to learn more about using these features in your app.

Follow the below steps to setup a push notification campaign from Amazon Pinpoint:

  1. Navigate to the AWS console either by visiting the AWS console, or running amplify console in your terminal, and selecting AWS console
  2. Search for and click on Amazon Pinpoint
  3. From the “All Projects” tab, select the Pinpoint resource you created when you configured your app with the Amplify CLI.
  4. Click on “Journeys” from the left side navigation menu
  5. Click on “Create journey”
  6. Set a name for the journey, and then click on “set entry condition”.
  7. Under “Choose how to start the journey”, select “Add participants from a segment.
  8. Click on “build a segment”, which will redirect you to a new screen.
  9. Enter a name to your segment, and under “base segments” select “include any audiences”, which will send a push notification to registered push notification tokens.
  10. Optional: You can also click on the “Add Criteria” button to setup filters for attributes on the push notification endpoint created in Pinpoint, allowing you to target specific segments of users.
  11. You can see at the bottom of the screen the estimates of how many endpoints are eligible to receive the push notification campaign based on the audience and criteria you have selected.
  12. Then, click on “Create segment”.
  13. Go back to the first tab with the journey information, and then click the refresh button next to the drop down menu “Segments”. You will see your newly created segment, select it.
  14. Click on save.
  15. Then, click on the plus sign that says “Add activity”, and select “send a push notification”.
  16. Click on “Create template”, this will open a new tab in your browser.
  17. Select “Push notifications” from the radio buttons at the top of the screen.
  18. Add a name and description to your push notifications template.
  19. Select “Standard message” from the “Notification type” section.
  20. Add a title and body to your message. Optionally, you can also select a custom alert sound, and determine if there is an action that should occur when the notification is clicked on. For now, keep the custom alert sound empty, and set the action to “Open your app”.
  21. Click on “Create”.
  22. Go back to the journey tab again, and click the refresh button to the right of the “Choose a push notification template” button.
  23. Then, click on the “choose a push notification template” button, and select the template you have created.
  24. Click on “Save”.
  25. Click on “Review” from the top right hand side, Pinpoint will show you if you have any issues with your configured Journey, then click on “Next”.
  26. You will see warnings about setting up a start time and testing your journey, but since we want to start the journey immediately you can just click on “Mark as reviewed”.
  27. Lastly, click on “Publish”. The journey screen will inform you how long it will take until it is started.
  28. After the journey started, if you check your emulator, you should see that a Push Notification was received.

Conclusion

In conclusion, AWS Amplify’s push notification support is a significant development that Android, Swift, Flutter, and React Native developers have been waiting on for a long time! With its simplicity, customization, and segmentation and targeting capabilities, it’s the perfect tool to keep your users engaged and informed.

Start building push notification enabled apps today by visiting our documentation.

Cleanup

To ensure that you don’t have any unused resources in you AWS account, run the following command to delete all the resources that were created in this project if you don’t intend to keep them.

amplify delete
Abdallah Shaban

Abdallah Shaban

Abdallah Shaban is a Senior Product Manager at AWS Amplify, helping Javascript and Flutter developers create apps that delight their users. When not working, Abdallah tries to keep himself updated on the newest innovations in tech, playing his guitar, and traveling.

Ashish Nanda

Ashish Nanda

Ashish Nanda is a Senior Software Engineer and Tech Lead at AWS Amplify. He leads design and engineering on the JavaScript and Flutter open source SDK teams with the goal of helping developers build full-stack web and mobile applications quickly & seamlessly using cloud services.