Azure function running Java for Android notifications

Azure function running Java for Android notifications

  • 91

Azure function running Java for Android notifications. We're going to explore how we can setup Pusher Beams on an Android client using an Azure Function running Java to trigger the notifications.

Introduction

Pusher Beams allows you to customize push notifications you send to your devices via a server. However it can be expensive to run a server 24 hours a day 7 days a week and we may only need to send notifications every so often. This is where Microsoft Azure Functions can help. Azure Functions are serverless and work on a pay as you go model (with a generous free tier). This means that you only pay for when you use the function. We’re going to explore how we can setup Pusher Beams on an Android client using an Azure Function running Java to trigger the notifications.

Prerequisites

  • A free Microsoft Azure account. You can create one here.
  • A free Pusher account. You can create one here.
  • Maven installed on your machine. Instructions here.
  • A free Google Firebase account. You can create one here.
  • Postman or another HTTP client installed on your machine. You can download Postman from here.
  • Android Studio 3.3.2+
  • An understanding of Android development and Android Studio environment.

Create your Android application

We will need to have a user that has registered for notifications and signed up for an interest we will call “hello”, so we can test out our implementation. We’re going to create a very basic Android app that doesn’t actually show anything to the user except for the notification on the lock screen.

Create a new Empty Activity project using Android Studio and name it something like AzurePusher. Provide a Package name and remember this as you will need it for completing the Firebase set up. We will be using Kotlin as the language choice for this tutorial and supporting Android 16+ (Jelly Bean).

Firebase set up

Log in to your Firebase account here and go to your console. If you do not already have a project created you will need to create one and name it anything you like, if you have a project select it. Within the Project Overview page select Add App and follow the instruction for creating a new Android application.

Once you have completed the setup for your Android app you will be returned to the dashboard. You will need to go to the project settings (found within the “settings cog” in the top left). Once in the project settings select the Cloud Messaging tab. Copy the Server Key you will need it for setting up your Pusher Beams instance.

Creating a Pusher Beams instance

Login or create an account to access your dashboard here. Create a new beams instance using the dashboard.

Complete step one of the Android setup guide, by providing your FCM server key you copied earlier and Continue. We will pick up the remainder later on in this tutorial. Press the X to exit the setup guide and you will be returned to your dashboard for that instance. Scroll to the bottom of the page and you will find your Pusher Beams instance ID and secret key, make note of these you will need them later.

Adding the SDKs

Open your app level build.gradle file and add the following into your dependencies:

    // app/build.gradle
    ...
    dependencies {
     ...
     implementation 'com.google.firebase:firebase-messaging:17.1.0'
     implementation 'com.pusher:push-notifications-android:1.4.0'
     ...
    }
    ...

Here we are adding the Firebase messaging SDK and the Pusher Beams SDK. You should already have the Google Service SDK and google-services.json added to your project when setting up the Firebase app.

Synchronize Gradle by pressing the Sync Now button.

Initialize Beams

Open your main activity and add the following import:

    // App/java/{your.package.name}/Main.activity
    import com.pusher.pushnotifications.PushNotifications

Add the following to your onCreate function:

    // App/java/{your.package.name}/Main.activity
    PushNotifications.start(applicationContext, "YOUR_INSTANCE_ID")
    PushNotifications.addDeviceInterest("hello")

Remember to replace YOUR_INSTANCE_ID with the instance id from your Pusher Beams console and run your application.

Create your Azure function

Creating a Pusher Beams instance

Log in or create an account to access your dashboard here. Create a new Pusher Beams instance using the dashboard.

Complete step one of the Android setup guide, by providing your FCM server key you copied earlier and Continue. We will pick up the remainder later on in this tutorial. Press the X to exit the setup guide and you will be returned to your dashboard for that instance. Scroll to the bottom of the page and you will find your Beams instance ID and secret key, make note of these you will need them later.

Creating our function

Log in to your Microsoft Azure portal here. Using the search facility (found at the top of the page) search for “Function App”.

Note: When searching make sure to sure for “Function App” and not “Function Apps”

Once you are on the function app page click Add to begin the process of adding a new Azure Function. You will need to give your app a name, this must be unique and you cannot use full stops. Try reverse domain naming like this: com-example-appname. I have used PusherBeams-Java-``Android. As long as the radio buttons are set to Create new, entering a name should also auto complete the resource group and storage. If it hasn’t you should complete these fields as well.

Select your Subscription and Hosting Plan. If you’re unsure what these should be leave them as the default values. We will also be using Windows OS for this tutorial and our location will be set to Central US. However feel free to alter the location if the Java run time is available there as well. Make sure your Runtime Stack is set to Java and click Create.

Once your resource has been created you should receive a notification on the navigation bar. If you don’t see this, wait a couple of minutes and refresh the page. Your resource should appear in a list of Function Apps. Select your resource.

Now you have created a Function App you need to create a Function. On the overview page select the button New Function or from the side bar click on the + the is next to the Functions drop down. You will be given a selection of ways to build your function, select the Visual Code option and click Continue. On the next page select the Direct Publish option and click Continue. Follow the instructions on the next page for installing and setting up for Visual Code, the Azure command line tools and the Azure Functions extension for Visual Studio Code. Make sure you have signed in to your Azure account in Visual Studio Code before continuing.

With Visual Code Studio open open the command palette (View → Command Palette). Select Create New Project. When prompted provide an empty directory for your project and select the language to be Java. Provide a group ID using a reverse domain name naming method. Complete the remaining steps as appropriate (you can just accept the default values).

Azure functions make it easy to invoke your code by hitting an HTTP endpoint. This is great for push notifications, as you can hit this endpoint using our HTTP rest client and passing in our message. You will see more of this later when you test your integration. For now all you need to know is that the default implementation will set this up for you.

Note: There are lots of other templates available for invoking your function and you may wish to explore these as well. You can always invoke your function from the portal if you wish to.

Once your project is setup you can deploy it straight from Visual Code, right click on the newly created src folder and select Deploy to Function App. Select the function app you created earlier for example Pusher-Beams-Java-Android. This will complete the deployment process for you, you can confirm the success by checking the terminal output in Visual Code Studio and by refreshing your Azure Portal.

Writing our function

The first thing we need to do in our function is install our dependencies. Open your pom.xml file and add the following to your dependencies (make sure it’s <dependencies> and not <dependencyManagement>):

    // pom.xml
    <dependencies>
      // ....
      <dependency>
        <groupId>com.pusher</groupId>
        <artifactId>push-notifications-server-java</artifactId>
        <version>1.1.0</version>
      </dependency>
      // ...
    </dependencies>

If prompted you should synchronize your project. Now open your Function.java and replace the contents of the file with the following:

    // src/main/java/{your/reverse/domain}/Function.java
    package YOUR_PACKAGE_NAME;

    import java.io.IOException;
    import java.net.URISyntaxException;
    import java.util.*;
    import com.microsoft.azure.functions.annotation.*;
    import com.pusher.pushnotifications.PushNotifications;
    import com.microsoft.azure.functions.*;
    public class Function {
        @FunctionName("HttpTrigger-Java")
        public HttpResponseMessage run(@HttpTrigger(name = "req", methods = { HttpMethod.GET,
                HttpMethod.POST }, authLevel = AuthorizationLevel.FUNCTION) HttpRequestMessage<Optional<Notification>> request,
                final ExecutionContext context) {
            String instanceId = "YOUR_INSTANCE_ID";
            String secretKey = "YOUR_SECRET_KEY";
            final Notification body = request.getBody().get();
            if (body == null) {
                return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
                .body("Please pass a string or in the request body").build();
            }
            PushNotifications beamsClient = new PushNotifications(instanceId, secretKey);
            List<String> interests = Arrays.asList("hello");
            Map<String, Map> publishRequest = new HashMap();
            Map<String, String> alertMessage = new HashMap();
            alertMessage.put("title", body.getTitle());
            alertMessage.put("body", body.getMessage());
            Map<String, Map> alert = new HashMap();
            alert.put("alert", alertMessage);
            Map<String, Map> aps = new HashMap();
            aps.put("aps", alert);
            publishRequest.put("apns", aps);
            try {
                beamsClient.publishToInterests(interests, publishRequest);
                return request.createResponseBuilder(HttpStatus.OK).body("Push Sent").build();
            } catch (IOException e) {
                e.printStackTrace();
                return request.createResponseBuilder(HttpStatus.INTERNAL_SERVER_ERROR).body("Push Failed").build();
            } catch (InterruptedException e) {
                e.printStackTrace();
                return request.createResponseBuilder(HttpStatus.INTERNAL_SERVER_ERROR).body("Push Failed").build();
            } catch (URISyntaxException e) {
                e.printStackTrace();
                return request.createResponseBuilder(HttpStatus.INTERNAL_SERVER_ERROR).body("Push Failed").build();
            }
        }
    }

This code will be used by our Azure function later on to publish notifications to devices that our registered for the hello interest. We retrieve the title and message from the request body before creating an object that the Pusher Beams library can use to publish our push notification. Remember to replace YOUR_INSTANCE_ID and YOUR_SECRET_KEY with the credentials from your Pusher Beams console. The above code has used an object Notification, this object is used to decode the request body.

Create a new file called Notification.java and add the following to fix the compiler warnings:

    // src/main/java/{your/reverse/domain}/Notification.java
    package YOUR_PACKAGE_NAME;
    public class Notification {
        private String title;
        private String message;  

        public Notification(String title, String message) {
          this.title = title;
          this.message = message;
        }

        public String getTitle() {
          return title;
        }

        public String getMessage() {
          return message;
        }

        @Override
        public String toString() {
          return "Notification={title=" + title + ",message=" + message + "}";
        }
    }

Next we need to comment out the auto-generated test case that Visual Studio Code has made for us. Go to FunctionTest.java and comment out the file. Alternatively you could get the test to pass if you wish.

Now we can deploy the correct code to, make sure you have saved all your files and deploy your code as you did before. Alternatively you can use the command palette and the Deploy to Function App command.

Return to your Azure Portal and your function app, select the HttpTrigger-Java (it may be named differently for you if you used a custom setup earlier in this tutorial) within the Functions dropdown. Click the Get function URL button and copy the URL for the default (Function key) and keep it somewhere safe. You will need it for testing your integration later on.

Testing our implementation

Open your Postman HTTP rest client and create a new POST request. Add the function URL, that you got from your Azure function earlier, to the URL field. This URL contains a secret key for invoking your function, anybody with this key could potentially invoke your function so you should not share it within the public domain. Within the body of the post request add the following:

    {
        "title": "hello",
        "message": "Just a friendly hello"
    }

Once you are done press the Send button at the bottom. If everything has worked as expected you should receive a push to your device.

Conclusion

We’ve learned how to create an Azure function using Java that can publish a push notification using Pusher Beams to an Android device. The source code for this tutorial can be found here.