You are here: Welcome to Kony MobileFabric Tutorial

Welcome to Kony MobileFabric Tutorial

Using Kony MobileFabric, you can build apps for iOS, Android, PhoneGap, JavaScript, and Kony JavaScript.

Kony MobileFabric Video


About this Video:

In this tutorial we show you step by step how to set up a trial Kony MobileFabric account, how to configure Kony mobile services such as identity, integration, messaging, and sync, how to add backend services to your application, and how to invoke backend services by using Kony MobileFabric SDKs.

Supported Platforms

  • iOS
  • Android
  • PhongeGap
  • JavaScript
  • Kony JavaScript
  

 

Kony MobileFabric How To

The following sections explain the steps to setup Kony MobileFabric, configure Salesforce account, configure Kony MobileFabric for your application. From start to finish, we walk you through each step, showing screen shots and giving detailed instructions to get you up and running quickly.

Overview

Kony MobileFabric is a Mobile Backend as a Service (MBaaS) provider that helps the developers build native and web apps for mobile. Various backend service are easily integrated with the application irrespective of whether the application is build by using iOS, Android, PhoneGap or JavaScript frameworks.

In this tutorial, you are going to create a CRM Salesforce application for iOS, Android, PhoneGap, and Kony Studio that authenticates the user against a Salesforce backend to retrieve Leads, Contacts and Accounts by using Kony MobileFabric.

Setting up MobileFabric Trial

To setup Kony MobileFabric, you need a Kony cloud account and atleast one development environment associated with your Kony  account. If you do not have Kony Cloud account, please register as new user at http://www.kony.com/products/mbaas/trial  and add your first development cloud.

If you already have Kony account, select existing user, provide your credentials and proceed.

Configuring Salesforce Account

You need Client ID and Client Secret from Salesforce to authenticate Kony MobileFabric application against Salesforce.

If you do not have an account already with Salesforce, sign up for free developer account trial.

Creating Connected Application

Once you log in to Salesforce, you need to create a connected application. Connected applications use OAuth2.0 protocol and provides tokens to access Salesforce APIs.

Once you create a connected application, and define the Oauth scopes, Salesforce in return provides with Consumer Key and Consumer Secret for authorizing the connected application. Make a note of Consumer key and consumer secret. You will be using these tokens when configuring Kony MobileFabric. These are referred as ClientID and ClientSecret in Kony MobileFabric Portal.

For more information on connected apps, refer to https://developer.salesforce.com/page/Connected_Apps.

The following are the necessary inputs required for creating connected application as shown below:

Note: On successful user login, Salesforce calls your callbackURL with an authorization code. For working with Kony MobileFabric, Salesforce callback has no much significance and could be anything.
In the sample CRM app,
callback URL is provided as http://localhost:8080

Generating Security Token

A security token is an automatically generated key that you must add to the end of your password to log in to Salesforce from an untrusted network.

To generate a security token, follow these steps:

  1. Log in to your Salesforce developer account.
  2. Navigate to User Menu > My Settings.

  3. Under the My Settings left pane, click Personal > Reset My Security Token.


  1. Click the Reset Security Token button. The security token is sent to your registered email address.

  1. Append this security token to the Salesforce password (password+security token) when accessing Salesforce from Kony MobileFabric.

    Note: The security token is not required to be appended to Salesforce password in production instance of KonyCloud because the KonyCloud IP addresses would be whitelisted in Salesforce.

Configuring Kony MobileFabric

Now that you have activated Kony MobileFabric cloud and set up Salesforce account configuration, you need to configure Kony MobileFabric.

 

Creating MobileFabric Application

To create MobileFabric app, follow these steps:

  1. Log in to your Kony Cloud portal.
  2. Click Apps in the left menu.
  3. Under the Applications tab in the Manage Apps page, click Add New App to add new applications.


    A new Kony MobileFabric application is created and you are navigated to the app configuration page.

  4. To change the app name, click the Edit button and rename the app, for example, CRMSalesForce.

  5. To change the icon, click the default icon and provide your custom icon.

    For more information about adding applications, click here.

Configuring Identity

Identity is a service that validates the authentication of your users before they can access your application. Kony MobileFabric allows various types of validations that include:

For your CRM app, you will be using Salesforce Authentication.

To add an identity service, follow these steps:

  1. Navigate to the Identity tab (default selection) in app configuration page.
  1. Click Add New Identity Service and select Configure New.

  2. Provide an identity name, for example, SFIdentity.

  3. From the Type of Identity drop-down list, select Salesforce as you are authenticating users against Salesforce in your CRM app.
  4. From the Auth Mode drop-down list, select the UserName/Password

    The URLs for Salesforce URL and Callback URL for Kony MobileFabric application are pre-populated.

  5. Provide the Salesforce ClientID and the Salesforce ClientSecret details that you saved from your Salesforce Account Configuration.

  1. Click Save to save your identity configuration.

To learn more on adding identity services, click here.

Configuring Integration

The Integration tab is where you configure services for your application.

To configure integration, follow these steps:

  1. To add integration services, navigate to the Integration tab in the App Configure page.
  2. Click Add Integration and select Configure New.

  3. Provide a name for integration service, for example, SFAccounts, by hovering the mouse on [Specify a name] field and clicking the Edit button.


  4. From the Endpoint Type drop-down list, select Salesforce.

  1. Under Select Authorization Service, select the Use Existing Identity Provider option, and then select the existing identity provider from the drop-down list.

    This will link your integration services to your existing identity provider and authenticates Salesforce services implicitly by passing Salesforce SSO token at the backend.

    Provide valid UserID and Password+Security Token of Salesforce developer account where your connected application is created, and click Continue.

    Note: The Salesforce Password must be appended with the Security Token that you generated from Salesforce account.

  2. From the Object drop-down list, select the Account. The system loads available operations for the selected object in the Operation drop-down list.

    The system fetches all the available objects and operations associated with your Salesforce account.

  3. From the Operation drop-down list, select the getAccount, and then click the Add Operation button.

    In the same way you can add all the required operations under SFAccount integration service created.

  1. Click Save to save your Integration configuration.

    Note: In the CRM sample application, the getAccounts operation is shown as an example.

  2. To edit or test the operation, click the Settings button and select Edit. In the window that opens, you can see that required metadata to run and test the service is already populated.

    Note: Click Sample Code (</>) option to see the sample code for how to make an integration service in different platforms.

    You can see Input parameters querystring  required to call the service in Input tab.

    You can see in the Output tab that all output parameters from the service and respective Xpath to parse the params from the Service response are pre-configured.

    Note: You can add the param by clicking the Add button or delete by selecting the param and clicking the Delete button.

    In the Advanced tab “HTTP headers”, you will notice that SFToken is pre-populated for Authorization header to enable service testing from Kony MobileFabric console.

  1. Provide the test value for querystring under the Input params tab and click the Test button to see the response and result.

    Here are sample queryString params for:

    • getAccounts
      SELECT name,type,BillingCity,BillingState,AnnualRevenue,website,Industry,phone,BillingStreet from Account where type!=null
    • getContacts
      SELECT ID,NAME,FIRSTNAME,LASTNAME,TITLE,PHONE,EMAIL FROM Contact
    • getLeads
      SELECT ID,NAME,FIRSTNAME,LASTNAME,TITLE,PHONE,EMAIL FROM Lead
    • getOpportunities
      SELECT name,Amount,CloseDate,Type,LeadSource,StageName,ExpectedRevenue,Probability from Opportunity

      Note: You can add configure new integration services for Contacts Leads and Opportunities or add all the operations to Single integration service. In this sample app, you have configured different integration services for getlead- “SFLead”,getOppotunity - “SFOpportunity” and getContact/updateContact- “SFContact”.

  2. Click Save to save your Operation service changes.

    To learn more on adding integration services, click here.

Configuring Synchronization

To add Synchronization service to Kony MobileFabric environment, follow these steps:

  1. Navigate to the Synchronization tab in App Configure page.
  2. Click Add Synchronization Scope and select Configure New.

  3. Under Sync Scope Definition, do the following:

    1. In the Namespace text box, provide a name for your sync scope.
    2. From the Integration Service drop-down list, select the service that you want to connect via sync server. Leave all the other settings to default.
  4. Click Save to save your sync scope.

    To learn more about defining sync scopes and objects, click here.

  5. Under Sync Objects, all the available objects are listed. Select the required operation to be executed through sync and click Generate attributes.

  1. You can edit the attribute properties as required. You can add relations or filters in the respective tabs and click Save.

    In the sample application, you will be creating  syncScopes for updateContact and getContact.

    If you have selected the Change Tracking Columns in Sync Scope definition, make sure that you are setting the last modified and soft delete attributes in the Change Tracking section of Sync Objects.

    Note: Sync is supported for Kony Studio and PhoneGap only. You can click Valid Sync Configuration to check whether Sync configuration defined is valid and to download the error log if any.

    For more information about Synchronization, click here.

Configuring Messaging

To configure Messaging for your Kony MobileFabric console, you need GCM key for Android and push certificates for iOS to register with Android and Apple push servers.

  1. Under Messaging, provide the GCM Key for Android, and click Save.

  1. For iOS, select the Application mode; upload the push certificates for iPhone, provide your certificate password, and click Save to save your configuration.

    To learn more on how to set up messaging environment on Kony MobileFabric portal, click here.

Publishing Services

After Kony MobileFabric configuration, publish services to cloud development server.

To publish services in MobileFabric, follow these steps:

  1. Navigate to the Publish tab under App Configuration page. All the available environments in your cloud account are listed.

  2. Click the environment name where you want to publish your services and click Publish.

    The publish progress can be seen by expanding the Details tab that appears at the bottom of the page.

    If publish is successful, you will see Published message under the environment you selected.

    You can access runtime services console for Integration, Sync, Messaging and Orchestration from here.

  1. To access app services console, click the icon  in Runtime services displayed under the environment where you published your services. You can also access synchronization and messaging consoles by clicking respective icons.

    In the App services console, within Integration Services, you can see all your integration services you configured in your Kony MobileFabric console.

    You can also test your runtime services here.

  2. Select an operation, getAccount, from the SFAccount integration service to see the environment URL where the service got published.

    Click the link to open service details page where you can test your runtime service by providing the accesstoken, instance URL and the queryString.

    You can get the instance URL and accesstoken from your Kony MobileFabric test service console or execute the below Curl command in your Windows or Linux command prompt to get access token and instance URL.

Sample Code to make Kony MobileFabric client initialization call from your app

To make Kony MobileFabric client initialization call from your app, follow these steps:

  1. To see how to make Kony MobileFabric client initialization call from your application on different platforms, click </> under the app name after successful publish.


  2. In the Sample Code window that appears, select the environment from drop-down list where the app is published. The sample code for initialization is generated.

  3. Click the respective platform tabs to see the initialization call signature.

    Important: Ensure that you make a note of “App ID”, ”App Secret” and “Service_URL”. These details are required to authenticate your application against Kony MobileFabric.

    The App service document and Sync Client code for PhoneGap and Kony Studio can be downloaded by clicking on the download icon () next to the published environment name.

    The app key and app secret can also be viewed by clicking on the Key icon () next to environment cloud name in the Publish screen.

Downloading Kony MobileFabric SDKs

Now that you have set up the Kony MobileFabric and published application to cloud, you will need to download Kony MobileFabric SDKs to start developing the applications.

To download required SDKs, navigate to SDKs section in the Manage Apps page, and then click required platform icon to download respective SDKs.

Note: Presently Kony supports Kony MobileFabric SDKs for native iOS, native Android, PhoneGap, JavaScript and Kony Studio.

Working with Kony MobileFabric

The first thing is to get a design for the application. You can use Kony Visualizer to design your application. To learn more on Visualizer, follow Visualizer tutorials  and Documentation.

After you have got a design, develop it for different platforms by using your choice of a programming language or tool.

Conclusion

In this tutorial, you have learned how to set up Kony MobileFabric, create an application with Salesforce authentication for iOS, Android, PhoneGap and Kony Studio by using Kony MobileFabric.

Github location for the apps:

Building iOS App using Kony MobileFabric

Overview

In this tutorial, you are going to use iOS SDK for Kony MobileFabric. iOS SDK can be downloaded from SDK section of Kony MobileFabric cloud.

You need to add the downloaded framework into your application into Frameworks section.

You need to import the framework into the files wherever you are using it.

#import <KonySDK/KNYSDK.h>

Initializing the SDK

Before using any of the Framework classes, you need to initialize the SDK with proper application configuration obtained from the MobileFabric portal you have created (like app key, app secret and service URL).

The KNYClient.h class initializes SDK.

NSString *appKey = _sampleConfiguration[@"appkey"];
    NSString *appSecret = _sampleConfiguration[@"appsecret"];
    NSString *serviceUrl = _sampleConfiguration[@"selflink"];
    
 
    [KNYClient loggingEnabled:YES];
    [[KNYClient sharedClient] initializeInBackgroundWithAppKey:appKey
                                                     appSecret:appSecret
                                              serviceURLString:serviceUrl
 completion:^(BOOL succeeded,NSError *error)
     {
         if (error) {
             
             UIAlertView *alert = [[UIAlertView alloc] initWithTitle:error.localizedDescription message:error.localizedRecoverySuggestion delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil, nil];
             [alert show];
             
         } else {
             NSLog(@"Successfully Configured");
             _isInitialized = YES;
         }
     }];

Authentication Over Kony MobileFabric

Once the SDK is successfully initialized,  you can use the rest of the services.

For authentication, you will be using  KNYIdentityService.h class.

NSString *identityName = _sampleConfiguration[@"identityname"];
    _authClient = [[KNYIdentityService alloc] initWithIdentityName:identityName];

You can authenticate on different service providers that are configured on the portal based on your requirement. Before authentication, you need to initialize the identity service by using you authentication provider.

if (_authClient) {
        [_authClient loginInBackgroundWithUsername:username password:password completion:^(BOOL succeeded,NSError *error) {
            block(succeeded,error);
        }];
    }

Once the identity service is initialized, you will be authenticating using loginInBackgroundWithUsername, Password and completion block providing the proper input values. The system returns a BooleanResultBlock block based on the response. This generates the required backend tokens to store and pass the required tokens in headers when invoking the integration services.

- (void)logoutUsingCompletionBlock:(void (^)(BOOL succeeded,NSError *error))block
{
    [_authClient logoutInBackgroundUsingCompletionBlock:^(BOOL succeeded,NSError *error) {
        block(succeeded,error);
    }];
}

For Log out, you need to call logoutInBackground method and it will return a BooleanResultBlock block.

Using Integration Service

To use integration services you need to initialize KNYIntegrationService.h  SDK class with the service name created on the portal side.

 _servcClient = [[KNYIntegrationService alloc]initWithServiceName:@"<Service Name>"];
_servcClient = [[KNYIntegrationService alloc] initWithServiceName:servicename];
    [_servcClient invokeOperationInBackgroundWithOperationName:operationName headers:nil parameters:parameters completion:^(NSDictionary* objects,NSError *error) {
        block(objects,error);
        NSLog(@"%@",objects);
    }];

Once it is successfully initialized, you can call over the required operation name to the integration service providing the necessary input parameters in the form of dictionary.

The system returns the response in the form NSDictionary if the call is successful, else it throws an error.

Using Messaging Service

To use a messaging service and registering for push notifications, you need to use KNYMessagingService.h

_kmsClient = [KNYMessagingService sharedMessagingService];

Initialize the service before using messaging services.

- (void)registerForPushNotifications:(NSData *)deviceToken
                          completion:(void (^)(BOOL succeeded,NSError *error))block
{
    NSString *deviceName = [UIDevice currentDevice].name;
    
    NSLog(@"%@",deviceToken);
    NSError *kmsError;
    
    _kmsClient = [KNYMessagingService sharedMessagingService];
    
    if(_kmsClient){
        [_kmsClient registerInBackgroundWithDeviceToken:deviceToken alias:deviceName completion:^(BOOL succeeded,NSError *error) {
            block(succeeded,error);
        }];
    }
    else{
        block(false,kmsError);
    }
}

Once the Messaging client is successfully initialized, you need to call registerInBackgroundWithDeviceToken: andAlias: usingBlock: method with the device token obtained from the APNS.

Similarly you will be calling  Unregister method to not receive notifications from MobileFabric.

[_kmsClient unregisterInBackgroundUsingCompletionBlock:^(BOOL succeeded,NSError *error)  block(succeeded,error) }];

In both the cases a Boolean block is resulted.

For more information, click here.

Running Sample Application

  1. Download the Kony MobileFabric iOS native app from github - https://github.com/kony/KonyMobileFabric_Demo_iOS

  1. Launch the project in your XCode. Navigate to MobileFabric_SDK folder and configure your app key, appsecret, serviceurl, identity name and queries to get Accounts, Contacts, Leads and Opportunities in the config.json file.
  2. Build and run the project.

    Note: To log in to app with your Salesforce credentials, you need to append the security token to the password.

    To validate or view messaging functionality, you need to install and run the app on a mobile device. Please note that Messaging does not work on Simulator.

  1. Launch the app on device and click Allow when prompted for Push notifications.
  2. Now log in to your Kony MobileFabric console, and navigate to the Publish tab under the Apps menu.

  1. Click Messaging icon under runtimes services of your environment where the Kony MobileFabric app is published.

    This opens your Messaging Services console for your app.

  1. Click General under Distribution in the left menu.
  2. On the right, select the Channel Type as Push Message and select your application for which you want to send the push notifications from the Associate Applications drop-down list.

    This will list all the subscribers subscribed to Kony Messaging Service from your application to receive push notifications.

  3. Select the subscribers you want to send the message.

  4. Specify the platform specific properties if any.
  5. Enter the message in message text field area provided.

  6. Set the Start and Expiry time and click Send. A notification appears on the user’s device where the application is installed.

Building Android App using Kony MobileFabric

Overview

Android SDK can be downloaded from SDK section of Kony MobileFabric cloud.

Let’s take brief look on how to use Android Kony MobileFabric SDK.

Initializing and Authenticating with Kony MobileFabric

Before you can use any Kony MobileFabric services, you need to authenticate against Kony MobileFabric. The Kony MobileFabric authentication service allows developers to connect to backend authentication sources, such as Active Directory or SalesForce, which are used for subsequent calls to back end services. It is assumed you have already created an authentication service in Kony MobileFabric and need to connect your Android application to the authentication services. Most applications have a login screen that allows the user to enter a username and password, and we will use this assumption going forward to work on authentication that uses a validate() method during the authentication process.

import com.kony.sdk.callback.IntegrationServiceCallback;
import com.kony.sdk.callback.LogoutCallback;
import com.kony.sdk.client.KonyFactory;
import com.kony.sdk.common.IdentityServiceException;
import com.kony.sdk.common.IntegrationServiceException;
import com.kony.sdk.common.KonyException;
import com.kony.sdk.services.identity.IdentityService;
import com.kony.sdk.services.integration.IntegrationService;
import com.konylabs.android.commons.AppUtils;

Before creating the validate method, you will need to import the Kony MobileFabric libraries. Add the above imports to the top of the LoginActivity class.

KonyClient client  = null;
IdentityService clientAuthentication = null;

Once the libraries are imported into the LoginActivity, you need to initialize a Kony MobileFabric Client object that is set in the ApplicationContext as well as add the validate method that will call the authentication services.

Additionally, you need to declare the clientAuthentication object as part of the LoginActivity:

KonyClient.initInBackground(getApplicationContext(), AppUtils.APPKEY,
     	   AppUtils.APPSECRET, AppUtils.SERVICE_URL, new InitCallback() {
		@Override
		public void onSuccess(JSONObject arg0) {
		// TODO Auto-generated method stub
		System.out.println("MBAAS succ"  );
		if(AppUtils.getAuthHeader()==null)
		progressDialog.cancel();
			}
		@Override
		public void onFailure(KonyException arg0) {
			if(AppUtils.getAuthHeader()==null)
			progressDialog.cancel();
			System.out.println("MBAAS fail " + arg0.getMessage());
			}

The KonyClient object stores the AppKey and AppSecret that you wrote down from the console. In your app, we store these values in a static object in AppUtils class.

The AppSecret and AppKey tell the Kony MobileFabric server that a valid application is communicating with the services. The service URL tells the Kony MobileFabric SDK where the services are located. This allows you to target different environments such as development, testing and production by using the same code while protecting and targeting the proper environment.

public void validate(View view) {
String username = ((EditText) findViewById(R.id.userid)).getText()
				.toString();
String password = ((EditText) findViewById(R.id.password)).getText()
				.toString();
		progressDialog.show();
		try {
			
		KonyFactory mbaasFactory = new KonyFactory();
// calling Identity service for Validating once authenticated success LoginCallback Success method will execute else Failure.
	clientAuthentication =	mbaasFactory.getIdentityService(AppUtils.PROVIDER);
	clientAuthentication.loginInBackground(username, 
password,new LoginCallback()

The validate method retrieves the username and password from the activity_login screen.  Once the username and password have been retrieved, you need to create new MbaaS factory object and  call the getIdentityService. When initializing the object, you will need to pass in the name of the Identity Provider.

Once the service has been initialized, you can call the loginInBackground method to authenticate the user. The LoginInBackground Methods requires the username, password and a callback method when it is invoked.

@Override
public void onSuccess(KonyUser arg0) {progressDialog.cancel();
					//register();
Intent intent = new Intent(LoginActivity.this,MenuActivity.class);
		AppUtils.setAuthObject(clientAuthentication);
					startActivity(intent);
		if(preference.getBoolean("login", false))
					   finish();
				}	
@Override
public void onFailure(IdentityServiceException exception) {
	// TODO Auto-generated method stub progressDialog.cancel();
JSONObject message = null;
try {
message = new JSONObject((String) exception.getMessage());
} catch (JSONException e1) {
	// TODO Auto-generated catch block
	e1.printStackTrace();
				}

The LoginCallback requires two methods to be overridden when it is called, the onSuccess and onFailure methods. When a login fails or there is a connection failure, the onFailure method is invoked. In the onSuccess method, we set the AuthObject and start a new activity.

Using Integration Service

Once you have authenticated the user, the application can then call Kony MobileFabric backend services. Let’s take a look at how we configured leads backend service.

The example below retrieves the authentication header and adds it as a parameter to the Kony MobileFabric call via a HashMap. If you want to pass additional parameters to the Kony MobileFabric service that you defined when you created the service, simply add them to the HashMap. When we get IntegrationService object from MbaasFactory. getIntegrationService(“SFLead”), you pass the service name of the Kony MobileFabric Service you created in the console. In the example below, the service is initialized to call the SalesForceLeads service. Once initialized, the invokeOperationInBackground method is called be sending the operation name of the service to be invoked, the parameters we created in the HashMap and a callback.

KonyFactory mbaasFactory = new KonyFactory();
  
 try {
	mbaasint = mbaasFactory.getIntegrationService("SFAccount");
			} catch (KonyException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
         jsonobj = AppUtils.getSFAccountsList();
         parameters.put("queryString", "SELECT name,type,BillingCity,BillingState,AnnualRevenue,website,Industry,phone,BillingStreet from Account where type!=null");

On success, the service returns a parsable JSON object. The example above returns the Leads fetched from the call to the getLeads operation of the SFLeads service defined in the Kony MobileFabric integration console.

For more information, click here.

Using Messaging Service

  1. Create a Google Cloud Messaging Sender ID (Project ID ) and API KEY. Generate this by visiting the site https://code.google.com/apis/console, and enable GCM option in the APIs tab.
  2. Open Credential tab in APIS & AUTH, and then click Create new Key and Android key.

  1. Update AppUtils.java with SENDER_ID and API_KEY at Kony MobileFabric.
    public void register()
    {
      context = getApplicationContext();
    if (checkPlayServices()) {
    gcm = GoogleCloudMessaging.getInstance(this);
    regid = getRegistrationId(context);
    registerInBackground();
    } else {
    Log.i("gcm registration","No valid Google Play Services APK found.");
    }
    }

    register() method at LoginActivity.java will register the app with GCM. Registration process will be handled in background method registerInBackground()

    private void registerInBackground() {
    Log.i("First Screen", "registerInBackground");
    new AsyncTask<Void, Void, Void>() {
    @Override
    protected Void doInBackground(Void... arg0) {
    Log.i("regId-----:::", "entered registerInBackground");
    try {
    if (gcm == null) {
    gcm = GoogleCloudMessaging.getInstance(context);
    }
    regid = gcm.register(AppUtils.getSenderID());
    } catch (IOException ex) {
    Log.i("Exception on recieving regid--:::", ex.toString());
     
    }
    return null;
    }
     
    }.execute(null, null, null);

    After the registration is success, GCM server will send the Registration Key will be handled by MBaasGCMReceiver.java.

    public class MBaasGCMReceiver extends WakefulBroadcastReceiver{
    MbaasFactory mbaasFactory ;
    static String receivedData;
    String regId;
    NotificationManager nm;
    Notification notification;
    SharedPreferences prefs;
    @Override
    public void onReceive(final Context context, Intent intent) {
    String action = intent.getAction();
    if(action.equalsIgnoreCase("com.google.android.c2dm.intent.REGISTRATION"))
    {
    try{
     regId = intent.getExtras().getString("registration_id");
      prefs = context.getSharedPreferences("MbaasRegistrationId",
         Context.MODE_PRIVATE);
       // Log.i("first screen", "Saving regId " + regId);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("registration_id", regId);
        
        editor.commit();
        mbaasFactory = new MbaasFactory();
        MessagingService  msgservice = mbaasFactory.getMessagingService();
        msgservice.registerInBackground(regId,AppUtils.getUserAccount(),AppUtils.getDeviceID(context),new  MbaasMessagingCallback() {
    @Override
    public void onSuccess(boolean arg0) {
    if(arg0 == true)
    {
    Log.d("MBaasGCMReceiver-> MbaasMessagingCallback -> success : ",""+arg0);
    }
    }
    @Override
    public void onFailure(MessagingServiceException arg0) {
    // TODO Auto-generated method stub
    Log.d("MBaasGCMReceiver-> MbaasMessagingCallback -> failure : ",""+arg0);
    }
    });  
    }catch(Exception e)
    {
    Log.d("MBaasGCMReceiver->catch -> e : ",""+e);
    }
      }
    else if(action.equalsIgnoreCase("com.google.android.c2dm.intent.RECEIVE"))
    {
    Notification(context,intent.getExtras().get("content").toString());
    }
    }
    

    Notification is used to handle incoming messages from server.

    Permissions and receiver declaration at Manifest file.

    <!-- GCM requires a Google account. -->
        <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    
        <permission
            android:name="com.kony.mbaas.demo.permission.C2D_MESSAGE"
            android:protectionLevel="signature" />
    
        <uses-permission android:name="com.kony.mbaas.demo.permission.C2D_MESSAGE" />
    
    In application tag: 
    
    <receiver
                android:name="com.kony.mbaas.demo.MBaasGCMReceiver"
                android:permission="com.google.android.c2dm.permission.SEND"
               ><intent-filter>
                    <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
                    <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                    <category android:name="com.kony.mbaas.demo" />
                </intent-filter>
            </receiver>
    

 

Running the Sample App

  1. Download the Kony MobileFabric Android native app from github - https://github.com/kony/KonyMobileFabric_Demo_Android
  1. Export project to Eclipse.

  1. Navigate to AppUtils.Java and configure required Kony MobileFabric metadata.
  2. Build and run the project.

    Note: You may need to install ADT plugin to eclipse to run Android project.

  1. To validate or view messaging functionality, you need to install and run the app on physical device.
  2. Launch the app on device and click Allow when prompted for Push notifications.
  3. Now log in to your Kony MobileFabric console, and navigate to the Publish tab under the Apps menu.

  4. Click Messaging icon under runtimes services of your environment where the Kony MobileFabric app is published. This opens your Messaging Services console for your app.

  5. Click General under Distribution in the left menu.
  6. On the right, select the Channel Type as Push Message and select your application for which you want to send the push notifications from the Published Applications drop-down list.

  7. This will list all the subscribers subscribed to Kony Messaging Service from your application to receive push notifications. Select the subscribers you want to send the message.

  8. Specify the platform specific properties if any.

  9. Enter the message in message text field area provided.

    Note: To log in to app with your Salesforce credentials, you need to append the security token to the password.

  10. Set the Start and Expiry time and click Send. A Push notification appears on the user’s device where your application is installed.

Building PhoneGap App Using Kony MobileFabric

Overview

PhoneGap is a web-based mobile development framework based on the Apache Cordova open-source project.

Download PhoneGap SDK from the SDK section of the Kony MobileFabric Cloud.

Initializing the SDK

Initialize the PhoneGap (Cordova) SDK by using the following code. The initialization method fetches the configuration from Kony MobileFabric.

init

//Sample code to initialize Kony MobileFabric Client

kony
MBaaS = new kony.cloud(); konyMBaaS.init("<appKey>","<appsecret>","<serviceURL>",successCallback, errorCallback);

Include the kony-sdk.js  file in to html files. You will find this file in the “js-sdk” folder of the downloaded SDK folder.

Using Identity Service (Authentication over Kony MobileFabric)

Once the SDK is successfully initialized, you can use the rest of the services. For authentication you will be using Auth service object.

Login with provider type as Basic

// Sample code to authenticate to Kony MobileFabric Client

var loginObj = {"_type" : "basic", "userid" : username,"password" : password };authServiceObj = konyMBaaS.auth(“ProviderName”);authServiceObj.login(loginObj,LoginSuccessCallback,LoginFailureCallback);

Get Backend Token

// Sample code to get backend token for provider

konyMBaaS.auth("CRM").getToken('false',function(data){},function(data){});

Logout

// Sample code to logout from auth service

authServiceObj.logout(logoutSuccessCallback,logoutFailureCallback);

Using Integration Service

The following methods invoke integration services that are configured in the Kony MobileFabric portal.

// Sample code to fetch the integration service details
var accountsIntegrationObj = konyMBaaS.integration("ServiceName");var post_data = {"Authorization" : "Bearer "+ token }; //passing Authorization header in data. Get token value from getToken accountsIntegrationObj.request("OperationName", post_data, accountsIntegrationSuccessCallback, accountsIntegrationFailureCallback);

Using Messaging Service

Subscribe

// Sample code to subscribe to messaging service

konyMBaaS.messaging().subscribe(osType,deviceId,pnsToken, email, SuccessCallback,FailureCallback);

Unsubscribe

// Sample code to unsubscribe from messaging service

konyMBaaS.messaging().unsubscribe(SuccessCallback,FailureCallback);

Running Sample App

Download Kony MobileFabric Android, iOS, PhoneGap apps from github.

Android –https://github.com/popcornapps/KonyMobileFabric_Demo_PhoneGap_Android

iOS –https://github.com/popcornapps/KonyMobileFabric_Demo_PhoneGap_iOS

Running iOS App

  1. Launch the project in your xCode.
  2. Navigate to www folder and configure your app key, appsecret, serviceurl, identity name in config.json file.
  3. Build and run the project.

    To validate or see messaging functionality, you need to install and run the app on a physical device. Please note that Messaging does not work on simulator.

  4. Launch the app on the device and click Allow when prompted for Push notifications.
  5. Now log in to your Kony MobileFabric console, and navigate to Publish tab under Apps menu.

  6. Click Messaging icon under runtimes services of your environment where the Kony MobileFabric app is published.

    This opens your Messaging Services console for your app.

  7. Click General under Distribution in the left menu.
  8. In the right page, select the channel type to Push Message and then select your application for which you want to send the push notifications from the Published Applications drop-down list.

    This will list all the subscribers subscribed to Kony Messaging Service from your application to receive push notifications.

  9. Select the subscribers you want to send the message.

  10. Specify the platform specific properties if any, enter the message in message text field area provided, set the start and expiry time and click Send. Notification appears on the user’s device where your application is installed.

Running Android App

  1. Export project to Eclipse.
  2. Navigate to MBaaS.Java and configure required Kony MobileFabric metadata.
  3. Build and run the project.

    Note: You may need to install ADT plugin to eclipse to run Android project.

    To validate or see messaging functionality, you need to install and run the app on physical device.

  1. Launch the app on device and click Allow when prompted for Push notifications.
  2. Now log in to your Kony MobileFabric console, and navigate to Publish tab under Apps menu.

  3. Click Messaging icon under runtimes services of your environment where the Kony MobileFabric app is published.


    This opens your Messaging Services console for your app.

  4. Click General under Distribution in the left menu.
  5. In the right pane, select the channel type to Push Message and select your application for which you want to send the push notifications from the Published Applications drop-down list.

    This will list all the subscribers subscribed to Kony Messaging Service from your application.

  6. To receive push notifications, select the subscribers you want to send the message.

  7. Specify the platform specific properties if any, enter the message in message text field area provided, set the start and expiry time and click Send. Notification appears on the user’s device where your application is installed.

Building Kony Studio App using Kony MobileFabric

Overview

Here we will see how we have built our sample CRM Salesforce application by using Kony Studio and Kony MobileFabric services.

As we already have Visualizer design, we can start our Kony project with importing the Visualizer Project to Kony Studio and integrating the JS logic.

Now let us get into the details on integrating Kony MobileFabric services with Kony Studio.

Configuring Kony MobileFabric SDKs in Kony Studio Project

We need JS/Kony Studio SDK downloaded from SDKs section of Kony MobileFabric console.

Extract the SDK file to find kony-sdk.js file. This needs to be copied to the modules folder of your application.

Now, we can use the APIs provided in JS SDK to communicate to Kony MobileFabric services. To get familiar with Kony Studio MobileFabric SDK APIs, click here.

Before integrating the services, the first step is to initialize the Kony MobileFabric client in the application to authenticate your application against Kony MobileFabric.

Initialization and Login

client = new kony.sdk(); //Creating MBaaS client instance 

The first step is to create a Kony MobileFabric client instance.

//MobileFabric client initialization using init method.
    client.init(MBaaSConfig.AppKey,// App key of application to use MBaaS APIs
     	MBaaSConfig.AppSecret,// App secret of application to use MBaaS APIs
     	 MBaaSConfig.ServiceURL,// URL for App's Service Document   
     	 initSuccessCallBack,//Initialization success callback 
      	initFailureCallBack);//Initialization failure callback

Initialize the Kony MobileFabric client by passing the appkey, appsecret and serviceURL that you got from Kony MobileFabric configuration. In our sample app we have configured these details in a global MBaaSConfig array in config.js module.

The AppSecret and AppKey tell the Kony MobileFabric server that a valid application is communicating with the services. The service URL tells the Kony MobileFabric SDK where the services are located.

Now we need to create an instance for getidentity to invoke login method and generate claims token and accesstoken which will be used in background when invoking Salesforce integration services.

//Let's make use of KonyMobileFabric client instance to invoke getIdentityService method 
	        identityInstance = client.getIdentityService(MBaaSConfig.IdentityService);
// Invoking login mehod using identityInstance will do login 
with the given credentials asynchronously and executes the given callback. 				
	     	identityInstance.login({"userid": frmLogin.textUserName.text,"password": frmLogin.textPassword.text},//salesforce credentials
	     	identitySuccess,//login success callback
	     	identityError );//login error callback

getIdentityService is the API used to invoke identity service. The identity service authenticates the user against Salesforce and generates claims token and accesstoken required to invoke Salesforce services at the background.

You need to provide a valid Salesforce userID and password+security token to invoke login method and generate tokens.

These methods are available in the sample app in Login.js  and InitializeMbaas.js.

Calling Integration Services

To invoke the Salesforce Services and get data for Accounts, Leads, Opportunities and Contacts, we need to invoke our integrating services.

//Making KonyMobileFabric client instance to invoke getIntegrationService method.
		accountsClient = client.getIntegrationService("SFAccount");//Accounts is service name and accountsClient is Accounts integration service instance
//accountsClient.invokeOperation(Accounts service name,headers,query params, SuccessCallback,FailureCallback);
	 	accountsClient.invokeOperation("getAccount",{},MBaaSConfig.getAccountQuery, accountSuccessCallback, integFailureCallback);

We create a getIntegration service object instance. We invoke the SalesForce services we defined in the Kony MobileFabric console by using the invokeOperation on getIntegrationService object.

In the example above, we are creating an instance of “SFAccount” integration service we configured on Kony MobileFabric console and calling “getAccount” operation by using the invokeOperation method.

The result from the invoke operation is captured in the invoke operation successcallback function. Here we parse the result and set the required fields to the segment widget.

The integration services are available in IntegrationServices.js module of our sample app.

Using Messaging Service

Now let’s look at how we configured messaging in our app.

When the app is launched, an alert is thrown for user consent to accept push notifications.

if(response==true)
	{
		if(kony.os.deviceInfo().name == "iPhone" ||kony.os.deviceInfo().name == "iPhone Simulator")
 		{
 			callbackiPhoneSetCallbacks();
			callbackiPhoneRegister();
 		}
 		else if(kony.os.deviceInfo().name=="android")
 		{
 			callbackAndroidSetCallbacks();
    		callbackAndroidRegister();
 		}
	}

On success alert handle, the register function is invoked to set callbacks and register device with push servers for Android or iOS based on the device OS type.

function callbackiPhoneSetCallbacks()
{
	var callbacksTable = {onsuccessfulregistration: regSuccessiPhoneCallback, onfailureregistration: regFailureiPhoneCallback, 
				onlinenotification: onlinePushNotificationiPhoneCallback, offlinenotification: offlinePushNotificationiPhoneCallback, 
				onsuccessfulderegistration: unregSuccessiPhoneCallback, onfailurederegistration: unregFailureiPhoneCallback}; 
	kony.push.setCallbacks(callbacksTable);
}
function callbackAndroidSetCallbacks()
{
	kony.print("\n\n callbackAndroidSetCallbacks  in\n\n");
    kony.push.setCallbacks({
        onsuccessfulregistration: regSuccessAndroidCallback,
        onfailureregistration: regFailureAndroidCallback,
        onlinenotification: onlinePushNotificationAndroidCallback,
        offlinenotification: offlinePushNotificationAndroidCallback,
        onsuccessfulderegistration: unregSuccessAndroidCallback,
        onfailurederegistration: unregFailureAndroidCallback
    });
    kony.print("\n\n callbackAndroidSetCallbacks out\n\n");
}

In callbacks , we set the handlers for device registration/deregistration success or failure with push servers; handlers for online/offline notification.

function callbackAndroidRegister()
{
    var configToRegister = {senderid: "<Enter Sender ID>"};
    kony.push.register(configToRegister);
}

function callbackiPhoneRegister()
{
	var notificationTypes = [0, 1, 2];
	kony.push.register(notificationTypes);
}

In Kony Studio, to register device with GCM or Apple configuration, use Kony's Push APIs.

For Android, pass GCM client ID that you got from Google console to Kony’s Push register API.

For iPhone, pass notification types array.

If the device is successfully registered to the GCM or Apple cloud, onsuccessfulregistration callback is triggered.

function regSuccessiPhoneCallback(regId)
{
	kony.print("\n\n regSuccessiPhoneCallback:-\n"+regId+"\n" );
    msgInstance = client.getMessagingService();
	deviceId = kony.os.deviceInfo().deviceid;
	msgInstance.register("iPhone",deviceId,regId,"kmsdemouser@kony.com" ,regSubscribeSuccess, regSubscribeFailure)
}

In Successcallabck, we create a messaging instance (msgInstance) by invoking Kony’s MobileFabric getMessagingService method.

Then we invoke register method on msgInstance to subscribe the device with Kony Messaging Service (KMS).

We pass the following parameters to the register method:

Note: Messaging works only on device.

These methods are available in the Messaging.js module of our Sample app.

Using Sync

For configuring Sync, we need to download the Sync files for Kony Studio from Kony MobileFabric console.

Extract the zip file and copy the KonySyncDDL.js, KonySyncLib.js, KonySyncScopes.js, and ContactModel.js to your modules folder in the Kony Studio project.

In our app we are using Sync to get and update the contact data from Salesforce.

function identitySuccess(res)
{
	syncObj=client.getSyncService();
	kony.print("sync object created sucessfully");
	function syncInitSuccess(params){
	kony.print("sync initialized sucessfully");
	}
	function syncInitFailure(error){
	kony.print("sync init failed with erro:"+JSON.stringify(error));
	}
	try{
		syncObj.init(syncInitSuccess,syncInitFailure);
	}catch(exp){
		kony.print("Sync init failed with exp:"+JSON.stringify(exp));
	}
	frmDashBoard.show();//show dashboard form
    kony.application.dismissLoadingScreen();
}

We are initializing the sync object in the login success callback of Kony MobileFabric login by using the Kony MobileFabric APIs.

Contact.getAll(getAllContactSuccessCallback, eventErrorCallBack);

On click of Contacts in Dashboard, we call getAll on Contact Object from ContactModel.js file. We need to pass success and error callback methods.

function getAllContactSuccessCallback(response)
	{
		var lblContactName,lblContactTitle;
		var contactList =[];
		var tempContact ={};
		if(response.length<=0)
		{
			alert("No records found please sync");
			kony.application.dismissLoadingScreen();
			frmContacts.show();
			return;
		}else{
			contactResponse = response;
			contactDetails=response;
			for(var i=0;i<response.length;i++)
			{
				tempContact={};
				tempContact.lblContactName=response[i]._FirstName+" "+response[i]._LastName;
				if(response[i]._Title==null||response[i]._Title==""||response[i]._Title=="null")
					tempContact.lblContactTitle="No Title";
				else
					tempContact.lblContactTitle=response[i]._Title;
				contactList.push(tempContact);
			}
			frmContacts.segContacts.removeAll();
			frmContacts.segContacts.setData(contactList);
			frmContacts.show();
			kony.application.dismissLoadingScreen();
		}
	}
function eventErrorCallBack(error)	
	{		
		alert(JSON.stringify(error));
		dismissSyncLoadingScreen();
	}	

If success, it checks if there is related data in mobile DB and if there is no data then it gives an alert message to use sync.

function syncStartSession(){
	
		showSyncLoadingScreen("Starting Sync Session")
		var config1=kony.sync;
		syncObj.startSession(config1);
		getContacts();
		dismissSyncLoadingScreen();
	}	

To Initialize sync and start syncing from server, we have provided a Sync button in contacts page. On clicking the Sync button, we call syncStartSession() method that starts the sync process and downloads data from server; stores in to mobile DB and then displays the data on contact form.

Running the Sample App

Now let’s build and run our Kony MobileFabric App for Android and iPhone.

  1. Download the Kony MobileFabric app for Kony Studio from github- https://github.com/kony/MobileFabric_CRMDemoSync_KonyStudio.
  2. Import project to Kony Studio and navigate to Modules folder.

  3. Open config.js and configure your Kony MobileFabric properties.
  4. Now build the project for iPhone/Android and run the app on emulators from Kony Studio.
  5. Provide valid Salesforce credentials and password+securityToken to log in to the app and explore it.

    Note: Click here to learn how to build and run app on Kony Studio.

  1. To validate or see messaging functionality, you need to install and run the app on physical device.
  2. Launch the app on device and click Allow when prompted for Push notifications.
  3. Now log in to your Kony MobileFabric console, and navigate to the Publish tab under the Apps menu.

  1. Click Messaging under runtimes services of your environment where the Kony MobileFabric app is published. This opens your Messaging Services console for your app.

  1. Click General under Distribution in the left menu.
  2. On the right, select the channel type as Push Message and select your application for which you want to send the push notifications from the Published Applications drop-down list.

    This will list all the subscribers subscribed to Kony Messaging Service from your application to receive push notifications.

  3. Select the subscribers you want to send the message.

  4. Specify the platform specific properties if any.
  5. Enter the message in message text field area provided.

  6. Set the Start and Expiry time and click Send. Notification appears on the user’s device where your application is installed.

    Note: To log in to app with your Salesforce credentials, you need to append the security token to the password.

Copyright © 2014 Kony, Inc. All rights reserved.