Skip to main content

Push Notification for Andriod MAF application via MCS

Part 1 : Configure MCS Backend with Google Project ID

Step #1: Register yourself for Google Cloud Messaging :

There are several tutorials available online to guide you to do this. Some examples :
http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/
https://mixpanel.com/help/reference/android-push-notifications

Once you have registered there are 4 things which are important and will be used in later part of this blog :
Project Number
Browser API Key
Name
Make sure the "Google Cloud Messaging for Android" is enabled for this Project. 





Step #2 : Configure MCS backend with the Step#1 details

Create an Mobile Backend. Then go to your Mobile Backend Settings page. There will be a default Client Application created for you. Click on Edit and do the following.




In the above picture

Application Name and ID = Google Project Name
API Key = Google Browser API Key
Sender ID = Google Project Number

Now your backend is configured and ready to send Push Notifications.
Next step is to configure your MAF application.

Part 2 : MAF application 

For a mobile app to receive push notification, the mobile app should "register" itself with MCS backend first. This is an one time activity. As a developer/designer you need to find a right component to call the register URI. I tried to do this inside LifeCycleListenerImpl, but it didn't work, so I moved it to my datacontrol class and made sure it is being called only once.
This registration process will intern register your app with Google Messaging Service.

Below are the important steps and code snippets for the MAF application.
1. Create a simple MAF application.
2. Create a PushNotificationListener class inside ApplicationController project.

import oracle.adfmf.framework.event.EventListener;

public class PushNotificationListener implements EventListener {
   
    public final static String PUSH_MESSAGE             =   "#{applicationScope.push_message}";
    public final static String MCS_REGISTRATION_STRING  =   "#{applicationScope.mcsregistrationString}";
    public final static String PUSH_ERROR               =   "#{applicationScope.push_errorMessage}";
    public final static String PUSH_DEVICE_TOKEN         =   "#{applicationScope.deviceToken}";  
   
    public PushNotificationListener() {
        super();
    }

    @Override
    public void onOpen(String token) {
        // Clear error in app scope
        AdfmfJavaUtilities.setELValue(PUSH_ERROR, null);       
        // Write the token into app scope       
        AdfmfJavaUtilities.setELValue(PUSH_DEVICE_TOKEN,token);
    }

    @Override
    public void onMessage(Event event) {
        String msg = event.getPayload();               
        //set push message to application scope memory attribute for
        //display in the view.
        AdfmfJavaUtilities.setELValue(PUSH_MESSAGE, msg); 
     }

    @Override
    public void onError(AdfException adfException) {
       
        Utility.ApplicationLogger.logp(Level.WARNING, this.getClass().getSimpleName(), "PushHandler::onError",
                                       "Message = " + adfException.getMessage() + "\nSeverity = " +
                                       adfException.getSeverity() + "\nType = " + adfException.getType());
        AdfmfJavaUtilities.setELValue(PUSH_ERROR, adfException.toString());
    }
}


3. Edit LifeCycleListenerImpl to implement PushNotificationConfig interface. This will require you to override 2 methods. You also need to update start() method of this class.

  public void start()  {
    Utility.ApplicationLogger.logp(Level.FINE, this.getClass().getSimpleName(), "LifeCycleListener::start()","Push is enabled for application");         
    EventSource evtSource = EventSourceFactory.getEventSource(EventSourceFactory.NATIVE_PUSH_NOTIFICATION_REMOTE_EVENT_SOURCE_NAME);
    evtSource.addListener(new PushNotificationListener());    
  }


    @Override
    public long getNotificationStyle() {
        return PushNotificationConfig.NOTIFICATION_STYLE_ALERT | PushNotificationConfig.NOTIFICATION_STYLE_BADGE | PushNotificationConfig.NOTIFICATION_STYLE_SOUND;
    }

    @Override
    public String getSourceAuthorizationId() {       
        String senderId = "<GOOGLE_PROJECT_ID>"; //
Google Project Number        ValueExpression ve = AdfmfJavaUtilities.getValueExpression("#{applicationScope.applicationId}", String.class);
        ve.setValue(AdfmfJavaUtilities.getAdfELContext(), senderId);
        return senderId;
    }


4.  Code snippets to register your app with MCS. (You also need to create a dummy REST connection)

// Step 1 : connect to MCS backend
        String mobileBackendUrl = "<URL_MCS>";
        //clear
        AdfmfJavaUtilities.clearSecurityConfigOverrides("<NAME_OF_DUMMY_CONN>");
        //override
        AdfmfJavaUtilities.overrideConnectionProperty("
<NAME_OF_DUMMY_CONN>", "restconnection", "url", mobileBackendUrl);
        String mobileBackendId =  "<MCS_BACKEND_ID>";
        String mbeAnonymousKey =  "<MBE_ANONYMOUS_KEY>";
        String appKey =    "<APP_KEY_FROM_MCS>";

        MBEConfiguration mbeConfiguration = new MBEConfiguration("
<NAME_OF_DUMMY_CONN>", mobileBackendId, mbeAnonymousKey, appKey,
                                                                 MBEConfiguration.AuthenticationType.BASIC_AUTH);

        mbeConfiguration.setEnableAnalytics(true);
        mbeConfiguration.setLoggingEnabled(true);

        mbeConfiguration.setMobileDeviceId(DeviceManagerFactory.getDeviceManager().getName());
        MBE mobileBackend = MBEManager.getManager().createOrRenewMobileBackend(mobileBackendId, mbeConfiguration);
       
        mobileBackend.getMbeConfiguration().getLogger().logFine("Anonymous authentication invoked from DC", this.getClass().getSimpleName(), "anonymousLogin"); 

// Step 2 : login to MCS backend
        Authorization authorization = mobileBackend.getAuthorizationProvider();
        try {
            authorization.authenticateAsAnonymous();
        } catch (ServiceProxyException e) {           
                Utility.ApplicationLogger.log(Level.SEVERE, e.getMessage());
        }

// Step 3 : configure MBE with device id
        String _token = (String) AdfmfJavaUtilities.getELValue("#{applicationScope.deviceToken}");
        mobileBackend.getMbeConfiguration().setDeviceToken(_token);
        String packageName = "<GOOGLE_PROJECT_NAME>"; // com.company.BookMyRoom
        mobileBackend.getMbeConfiguration().setGooglePackageName(packageName);

// Step 4 : call register in a thread
        Runnable mcsJob = new Runnable(){

          public void run(){                                              
             try {
                 Notifications notification = mobileBackend.getServiceProxyNotifications();
                 String registrationInfo = notification.registerDeviceToMCS();
                 AdfmfJavaUtilities.setELValue("#{applicationScope.mcsregistrationString}", registrationInfo);
               } catch (ServiceProxyException e) {
                     Utility.ApplicationLogger.log(Level.SEVERE, e.getMessage());
               }
              //ensure main thread is synchronized with result
              AdfmfJavaUtilities.flushDataChangeEvent();
          }
        };
       
        ExecutorService executor = Executors.newFixedThreadPool(2);
        executor.execute(mcsJob);
        executor.shutdown();

5. Make sure the above code snippet gets called while you open the app for the first time. What I did was. created a simple app with 1 feature, with a taskFlow. Taskflow does a method call which executes the above snippet and then opens a simple AMX page. 

Part 3 : Send a Push Notification using JQuery

I have used a simple HTML page to test my push notification setup. But you can also test your setup from MCS itself. (In Mobile Backend > Notifications)

In my HTML I have button which call the below function to send a pre-defined message.

In below javascript :
ENCODED_USER_NAME_AND_PASSWORD : is the encoded user name and password in base64. I used www.base64encode.org to encode. Your encode string should be: username:password, i.e., xyz:abc. If xyz is your username and abc is your password to login to MCS.

    function SendPushNotification() {
    var dataInput = {
        "message": "Test Message",
    };
    $.ajax({
        url: "<URL_OF_MCS>/mobile/system/notifications/notifications",
        headers:
            {
                'Authorization' : 'Basic <ENCODED_USER_NAME_AND_PASSWORD>',
                'oracle-mobile-backend-id' : '<MCS_BACKEND_ID>'
            },
        method: "POST",
        contentType: "application/json; charset=UTF-8",
        dataType: "json",
        data: JSON.stringify(dataInput),
        processData: true,
        error: function (xhr) {
            alert("error: " + xhr);
        }
    });
    }


Acknowledgements :
Special Thanks for Arjan Kramer(@arjankramer) for the contribution on JQuery part. 
Many thanks to Frank Nimphius (@fnimphiu) for MCSSampleAndUtilities.


Comments

  1. Is this above example for Oracle MCS and Oracle MAF?Would you know if Oracle provides any demo access to MCS?

    ReplyDelete
    Replies
    1. Hi Deepika,

      Oracle does provide demo access to MCS for partners. You need to ask your Oracle contact for more details, it may vary country to country and partner to partner.
      Hope this helps.

      - Soham

      Delete
  2. Thanks for sharing. One thing, to add, that will help the reader a lot. There is a tool for base64 encoding
    url-decode.com/tool/base64-encode
    that tool also contains the 100+ web utilities for the users and developers as well.

    ReplyDelete

Post a Comment

Popular posts from this blog

Chatbots and Oracle Cloud Services

Thanks to Oracle A-Team, I had a chance to work with Chatbots. 3 pure NodeJS applications, on couple of Oracle Cloud platforms and Facebook messenger, and my chatbot was running. Let me explain, the architecture a bit. To start with, following is the simple representation of how it works. Message Platform Server : Is a NodeJS application, deployed on Oracle Application Container cloud, acts as a channel between Facebook Messenger and the chatbot engine. It simply converts the incoming messages from Facebook and sends it to chatbot readable format. Also, when chatbot replies, it converts to Facebook readable formats and passes it to messenger. Chatbot Engine : Is a NodeJS application, which communicate with some REST APIs based on a conversation flow document and moves the flow of the conversation from one state to another. Flow JSON : Where we document, every state of a conversation and which APIs to call to generate a response. For example, at the beginning of the con

Create Micro CRUD services for Oracle Database Cloud using NodeJS

I will try to explain, how you can use NodeJS to create mirco services for the tables in your Oracle Database Cloud or on-premise Database. Complete Github project : https://github.com/sohamda/LeasifyAPIs You need to do "npm install" to download the node_modules. Step by Step guide : 1. NodeJS : either 32 or 64 bit. If you already have NodeJS installed, please check whether it is 64 or 32. Use below command to figure that out : C:\>node > require('os').arch() If you get : 'ia32' , then it is 32 bit installation. 2. Install oracle-db node module .  This was a lengthy and time consuming installation for me, because for Windows, it has a lot of pre-requisites. If you are a Mac user, you are lucky. :) I followed : https://community.oracle.com/docs/DOC-931127 There is also a detailed one in github : https://github.com/oracle/node-oracledb/blob/master/INSTALL.md 3. Config your DB Cloud Create a user and couple of tables on which we'

Layout Management & CSS Classes with Oracle JET

Oracle JET provides automatic responsive layout using CSS classes. So that, from large screens to small screens the application fits itself the best possible way. JET’s layout management are based on 2 types of CSS classes “Responsive Grid” and “Flex”. Responsive grid classes which deals with size, number of columns and functions of a particular <div>. Naming convention of these classes are oj- size - function - columns sizes can be: sm, md, lg, xl functions can be: hide, only-hide columns can be: any number between 1 to 12.   Just like Bootstrap, JET also divides the width of the available space into 12 columns, so for example, if you want a section of your page should take up atleast 5 columns if you divide the available screen into 12 columns, you need use : oj- size -5. Now comes the size part, you need to define that for each size of the screen, from hand-held mobile devices to large or extra large desktop screens. With combination with theses grid c