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");
//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());
}
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);
mobileBackend.getMbeConfiguration().setDeviceToken(_token);
String packageName = "<GOOGLE_PROJECT_NAME>"; // com.company.BookMyRoom
mobileBackend.getMbeConfiguration().setGooglePackageName(packageName);
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();
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.
Is this above example for Oracle MCS and Oracle MAF?Would you know if Oracle provides any demo access to MCS?
ReplyDeleteHi Deepika,
DeleteOracle 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
Thanks for sharing. One thing, to add, that will help the reader a lot. There is a tool for base64 encoding
ReplyDeleteurl-decode.com/tool/base64-encode
that tool also contains the 100+ web utilities for the users and developers as well.