6 Android Applications

If you are an Android app developer, you can use the SDK that Oracle Mobile Cloud Service (MCS) provides for Android. This SDK simplifies authentication with MCS and provides native wrapper classes for MCS platform APIs.

Getting the SDK for Android

To get the MCS client SDK for Android, go to the Oracle Technology Network’s MCS download page.

To use the MCS SDK for Android, you should have the following software on your system:

Contents of the Android SDK

The following SDK libraries (JAR files) are included in the Android SDK:

  • mcs–android-sdk-shared-<version-number>.jar - The base library for the SDK, including functionality required by the other libraries as well as utility classes for accessing and authenticating with mobile backends.

  • mcs-android-sdk-analytics-<version-number>.jar - The Analytics library, which lets you insert custom events into your code that can then be collected and analyzed from the Analytics console.

  • mcs-android-sdk-location-<version-number>.jar - The Location library, which lets you access details about location devices that have been registered in MCS and the places and assets they are associated with.

  • mcs-android-sdk-fcm-notifications-<version-number>.jar - The Notifications library for FCM, which lets you set up your application to receive notifications sent from your mobile backend. If your app still uses GCM, the SDK also includes /gcm/mcs-android-sdk-notifications-<version-number>.jar. (The two notifications modules can’t be used at the same time.)

  • mcs-android-sdk-social-<version-number>.jar - The Social Login library, which allows you to set up your app to use Facebook login.

  • mcs-android-sdk-storage-<version-number>.jar - The Storage library, which lets you write code to access storage collections that are set up with your mobile backend.

  • mcs-android-sdk-sync-<version-number>.jar - The Sync Client library, which allows you to cache application data when the device running your app is disconnected from the network, then sync up the data when the network connection is reestablished.

  • IDMMobileSDK.jar - The identity management library used by all applications.

The SDK also includes these tools and examples:

  • mcs-tools.zip - The MCS Custom Code Test Tools, a set of command line tools for debugging custom APIs that you have associated with your app's mobile backend. Detailed instructions are located in the README file included in the zip.

  • mobile-log-download.zip - A command-line tool that allows you to download logs from MCS for viewing or archiving.

  • oracle_mobile_cloud_config.xml - A sample configuration file. You can adjust its properties based on the environment details of the mobile backend that your app will use and then copy the file to the assets folder you created when adding the SDK to your app.

  • examples.zip - Sample mobile apps that demonstrate how to use the SDK.

  • Javadoc.zip - Complete SDK API documentation. You can also reference the API documentation online: https://docs.oracle.com/en/cloud/paas/mobile-cloud/mcssa/index.html

Android SDK Dependencies

The SDK is modular, so you can package just the libraries that your app needs. Just be aware of the following dependencies:

  • Every Android application developed for MCS must have the shared (oracle-mobile_android_shared-<version-number>.jar) and IDMMobileSDK.jar libraries.

  • If the Storage library is installed, the Sync Client library must also be installed.

Adding the SDK to an Android App

  1. If you haven’t already done so, unzip the Android SDK zip.

  2. Copy the SDK jars into the /libs folder in your app's project. If this folder doesn't exist, create it at the same level in your hierarchy as your /src and /build folders.

  3. Decide which notifications library you need (FCM or GCM) and delete the .jar you are not using: mcs-android-sdk-fcm-notifications-<version-number>.jar or /gcm/mcs-android-sdk-notifications-<version-number>.jar. These modules can’t be used at the same time.

  4. In the source tree for the application, create a folder called /assets (at the same level as the /java and /res folders).

  5. In the SDK bundle, locate the oracle_mobile_cloud_config.xml file and copy it to the /assets folder.

  6. In your app's build.gradle file, make sure the following are among the dependencies registered so that the SDK libraries are available to the app.

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        compile 'org.slf4j:slf4j-jdk14:1.7.13'
    }
  7. Open /assets/oracle_mobile_cloud_config.xml and fill in the environment details for the mobile backend that the app will be using. See Configuring SDK Properties for Android.

Upgrading an Android App from SDK 17.x and Before

  1. Remove the following SDK jar files from the libs folder in your app's project (if they exist):
    • IDMMobileSDK.jar

    • IDMMobileSDK.zip

    • mcs-android-sdk-vanalytics-<version>.jar

    • mcs-android-sdk-vIDMSDK-<version>.jar

    • mcs-android-sdk-vlocation-<version>.jar

    • mcs-android-sdk-vnotifications-<version>.jar

    • mcs-android-sdk-vshared-<version>.jar

    • mcs-android-sdk-vsocial-<version>.jar

    • mcs-android-sdk-vstorage-<version>.jar

    • mcs-android-sdk-vsync-<version>.jar

  2. Unzip the new MCS Android SDK zip if you haven’t already.

  3. Copy the new SDK jar files into the libs folder in your app's project.

  4. Decide which notifications library you need (FCM or GCM) and delete the .jar you are not using: mcs-android-sdk-fcm-notifications-<version-number>.jar or /gcm/mcs-android-sdk-notifications-<version-number>.jar. These modules can’t be used at the same time.

  5. In your app's settings.gradle file, make sure that IDMMobileSDK is NOT an include. (Remove it if it is.)

  6. In your app's build.gradle file, make sure the following is removed from the dependencies registered:

        compile project(':IDMMobileSDK')
    
  7. In your app's build.gradle file, add the following to the dependencies registered:

        compile 'org.slf4j:slf4j-jdk14:1.7.13'
    

    So, the final dependencies should include:

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        compile 'org.slf4j:slf4j-jdk14:1.7.13'
    }

Follow the rest of the instructions in this chapter to configure SDK properties and your Android manifest file.

Configuring SDK Properties for Android

To use the SDK in an Android app, you need to add the oracle_mobile_cloud_config.xml configuration file to the app and fill it in with environment details for your mobile backend. In turn, the SDK classes use the information provided in this file to access the mobile backend and construct HTTP headers for REST calls made to APIs.

You package the configuration file in your app’s main bundle in the assets folder at the same level as the java and res folders. For example, in the demo application FixItFast, it’s in /app/src/main/assets.

The following code sample shows the structure of a oracle_mobile_cloud_config.xml file.

<mobileBackends>
  <mobileBackend>
    <mbeName>MBE_NAME</mbeName>
    <mbeVersion>MBE_VERSION</mbeVersion>
    <default>true</default>
    <appKey>APPLICATION_KEY</appKey>
    <baseUrl>BASE_URL</baseUrl>
    <networkConnectionTimeOut>CONNECTION_TIMEOUT</networkConnectionTimeOut>
    <enableAnalytics>true</enableAnalytics>
    <enableLogger>true</enableLogger>
    <authorization>
      <offlineAuthenticationEnabled>true</offlineAuthenticationEnabled>
      <authenticationType>AUTH_TYPE</authenticationType>
      <oauth>
        <oAuthTokenEndPoint>OAUTH_URL</oAuthTokenEndPoint>
        <oAuthClientId>CLIENT_ID</oAuthClientId>
        <oAuthClientSecret>CLIENT_SECRET</oAuthClientSecret>
      </oauth>
      <basic>
        <mobileBackendID>MOBILE_BACKEND_ID</mobileBackendID>
        <anonymousKey>ANONYMOUS_KEY</anonymousKey>
      </basic>
    </authorization>
    <!-- additional properties go here -->
  </mobileBackend>
</mobileBackends>

Here’s a list of the file’s elements. The values that you need to fill in for a given mobile backend can be found on the Settings and Clients pages for that mobile backend.

  • mobileBackends — The config file’s root element, containing one or more mobileBackend elements.

  • mobileBackend — The element for a mobile backend.

  • mbeName — The name of the mobile backend associated with your app.

  • mbeVersion — The version number of your app (for example, 1.0).

  • default — If true, that mobile backend is treated as the default and thus can be easily referenced using the getDefaultMobileBackend(Context context) method in the SDK’s MobileBackendManager class.

  • appKey — The application key, which is a unique string assigned to your app when you register it as a client in MCS. This key is only required if you are using notifications. See Registering an App as a Client in MCS.

  • baseUrl — The URL your app uses to connect to its mobile backend.

  • networkConnectionTimeOut — (Optional) The connection timeout value in seconds. The default is 60 seconds. This element was added in 17.4.5.

  • enableLogger — When set to true, logging is included in your app.

  • enableAnalytics — When set to true, analytics on the app’s use can be collected.

  • authorization — Use the sub-elements of this element to define the authentication the app will be using and specify the required credentials.

    • offlineAuthenticationEnabled — If set to true, offline login will be allowed. For this to work, you also need to add the following to the app’s AndroidManifest.xml file:
      <receiver android:name="oracle.cloud.mobile.network.NetworkHelper"
        <intent-filter>
          <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
      </receiver>
    • authenticationType — Define the kind of authentication mechanism being used to connect your app to MCS. Possible values are oauth (for OAuth Consumer) , basic (for HTTP Basic), sso, tokenAuth (for SSO token exchange), and facebook (for logging in with Facebook credentials). If this element isn’t specified, OAuth Consumer is used. The other contents and sub-elements of the authorization element depend on the type of authentication.

OAuth Consumer

For OAuth, set the value of the <authenticationType> element to oauth and fill in the OAuth credentials provided by the mobile backend.
  • oAuthTokenEndPoint — The URL of the OAuth server your app goes to, to get its authentication token.

  • oAuthClientId — The unique client identifier assigned to all apps when they’re first created in your mobile backend.

  • oAuthClientSecret — The unique secret string assigned to all apps they’re first created in your mobile backend.

The resulting authorization element might look something like this:

<authorization>
  <offlineAuthenticationEnabled>true</offlineAuthenticationEnabled>
  <authenticationType>oauth</authenticationType>
  <oauth>
    <oAuthTokenEndPoint>http://oam-server.oracle.com/oam/oauth2/tokens</oAuthTokenEndPoint>
    <oAuthClientId>f2d3ca5c-7e6f-4d1c-aabc-a2f3caf7ec4e</oAuthClientId>
    <oAuthClientSecret>vZMRkgniIbhNUiPnSRT2</oAuthClientSecret>
  </oauth>
</authorization>

Enterprise SSO

For SSO, set the value of the <authenticationType> element to sso, fill in the OAuth credentials provided by the mobile backend, and add the ssoTokenEndpoint.

The resulting authorization element might look something like this:

<authorization>
  <offlineAuthenticationEnabled>true</offlineAuthenticationEnabled>
  <authenticationType>sso</authenticationType>
  <oauth>
    <oAuthTokenEndPoint>host/mobile/platform/sso/token</oAuthTokenEndPoint>
    <oAuthClient>f2d3ca5c-7e6f-4d1c-aabc-a2f3caf7ec4e</oAuthClient>
    <oAuthClientSecret>vZMRkgniIbhNUiPnSRT2</oAuthClientSecret>
    <ssoTokenEndpoint>https://development-mcspmtrial90.mobileenv.oracle.com:443/mobile/platform/sso/token</ssoTokenEndpoint>
</oauth>
</authorization>

SSO with a Third Party Token

For SSO with a third-party token, set the value of the <authenticationType> element to tokenAuth. You also need to fill in authentication credentials provided by the mobile backend, depending on how you have integrated the token issuer.

If you are using JWT tokens and have integrated the token issuer by registering a configuration via a policy in MCS, you need to nest the mobile backend’s OAuth credentials. The resulting authorization element might look something like this:

<authorization>
  <offlineAuthenticationEnabled>true</offlineAuthenticationEnabled>
  <authenticationType>tokenAuth</authenticationType>
  <oauth>
    <oAuthTokenEndPoint>http://oam-server.oracle.com/oam/oauth2/tokens</oAuthTokenEndPoint>
    <oAuthClientId>f2d3ca5c-7e6f-4d1c-aabc-a2f3caf7ec4e</oAuthClientId>
    <oAuthClientSecret>vZMRkgniIbhNUiPnSRT2</oAuthClientSecret>
  </oauth>
</authorization>

If you have integrated the IdP token issuer by uploading certificates into MCS, you need to nest the mobile backend’s HTTP Basic credentials. The resulting authorization element might look something like this:

<authorization>
  <offlineAuthenticationEnabled>true</offlineAuthenticationEnabled>
  <authenticationType>tokenAuth</authenticationType>
  <basic>
    <mobileBackendID>6d3744b8-cab2-479c-998b-ebba2c31560f</mobileBackendID>
    <anonymousKey>UFJJTUVfREVDRVBUSUNPTl9NT0JJTEVfQU5PTll</anonymousKey>
  </basic>
</authorization>

HTTP Basic

For HTTP Basic authentication, you need to set the value of the <authenticationType> element to basic and fill in the HTTP Basic auth credentials provided by the mobile backend.
  • mobileBackendID — The unique identifier assigned to a specific mobile backend. It gets passed in an HTTP header of every REST call made from your app to MCS, to connect it to the correct mobile backend. When calling platform APIs, the SDK handles the construction of the authentication headers for you.

  • anonymousKey — A unique string that allows your app to access APIs that don’t require login. In this scenario, the anonymous key is passed to MCS instead of an encoded user name and password combination.

The resulting authorization element might look something like this:

<authorization>
  <offlineAuthenticationEnabled>true</offlineAuthenticationEnabled>
  <authenticationType>basic</authenticationType>
  <basic>
    <mobileBackendID>6d3744b8-cab2-479c-998b-ebba2c31560f</mobileBackendID>
    <anonymousKey>UFJJTUVfREVDRVBUSUNPTl9NT0JJTEVfQU5PTll</anonymousKey>
  </basic>
</authorization>

Facebook

For Facebook login, you need to set the value of the <authenticationType> element to facebook, fill in the HTTP Basic auth credentials provided by the mobile backend, and add the facebook element, where you specify the Facebook credentials.
  • facebookAppId — The Facebook application ID.

  • scopes — You can use this element to specify Facebook permissions (optional).

The resulting authorization element might look something like this:

<authorization>
  <offlineAuthenticationEnabled>true</offlineAuthenticationEnabled>
  <authenticationType>facebook</authenticationType>
  <basic>
    <mobileBackendID>6d3744b8-cab2-479c-998b-ebba2c31560f</mobileBackendID>
    <anonymousKey>UFJJTUVfREVDRVBUSUNPTl9NT0JJTEVfQU5PTll</anonymousKey>
  </basic>
  <facebook>
    <facebookAppId>123456789012345</facebookAppId>
    <scopes>public_profile,user_friends,email,user_location,user_birthday</scopes>
  </facebook>
</authorization>

Configuring Your Android Manifest File

Permissions for operations such as accessing the network and finding the network state are controlled through permission settings in your application's manifest file, AndroidManifest.xml. These permissions are required:

  • permission.INTERNET — Allows your app to access open network sockets.

  • permission.ACCESS_NETWORK_STATE — Allows your app to access information about networks.

Other permissions are optional. For example, the Analytics platform API uses location to provide detailed information about the usage and performance of your app. If you’re including the Analytics library from the SDK, you’ll want to add these permissions as well.

  • permission.ACCESS_COARSE_LOCATION— Allows your app to access approximate location information, derived from sources such as wi-fi and cell tower positions.

  • permission.ACCESS_FINE_LOCATION — Allows your app to access precise location information, derived from sources such as GPS.

For more information about permissions in your Android application, see Android Manifest Permissions in the Google documentation.

Add the permissions at the top of your AndroidManifest.xml file, as shown in the following example:


<?xml version="1.0" encoding="UTF-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="oracle.cloud.mobile.photobox" >
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
</manifest>

Note:

Versions of the SDK before 17.4.5 used a NetworkHelper class that is no longer required. If your manifest file includes the following section, it can be deleted:
<application>
    <receiver android:name="oracle.cloud.mobile.network.NetworkHelper"
      <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
      </intent-filter>
    </receiver>
    (.....)
</application>

Adding the SDK to your application may require you to configure your AndroidManifest.xml file to add new permissions or activities. For example, if you add the Notifications individual SDK library, you may also need to add a new broadcast receiver. For more information, see Setting Up a Mobile App for Notifications.

Loading a Mobile Backend's Configuration into an Android App

For any calls to MCS APIs using the Android SDK to successfully complete, you need to have the mobile backend’s configuration loaded from the app’s oracle_mobile_cloud_config.xml file. You do this using the MobileBackendManager and MobileBackend classes:

MobileBackendManager.getManager().getMobileBackend("My_Backend_Name")

Authenticating and Logging In Using the SDK for Android

Here is some sample code that you can use for authentication through MCS in your Android apps.

OAuth Consumer

First you initialize the authorization agent and set the authentication type to OAUTH.

private AuthorizationAgent mAuthorization; 
private MobileBackend mobileBackend; 
Context mCtx = getApplicationContext();
mobileBackend = MobileBackendManager.getManager().getDefaultMobileBackend(mCtx);
mAuthorization = mobileBackend.getAuthorization(AuthType.OAUTH);

Then you use the authenticate method to attempt authentication. The call includes parameters for Android context, user name, password, and a callback that completes the authorization process.

TextView username, password; 
username = (TextView) findViewById(R.id.username);
password = (TextView) findViewById(R.id.password); 
String userName = username.getText().toString(); 
String passWord = password.getText().toString();
mAuthorization.authenticate(mCtx, userName, passWord, mLoginCallback); 

Here’s the definition for the callback.

AuthorizationCallback mLoginCallback = new AuthorizationCallback() {
   @Override
   public void onCompletion(ServiceProxyException exception) {
     Log.d(TAG, "OnCompletion Auth Callback");
      if (exception != null) {
        Log.e(TAG, "Exception while receiving the Access Token", exception);
     } else {
        Log.e(TAG, "Authorization successful");
     }
   }
 }

Enterprise SSO

First you initialize the authorization agent and set the authentication type to SSO. (For SSO third-party token exchange, see the next example.)

private AuthorizationAgent mAuthorization; 
private MobileBackend mobileBackend; 
Context mCtx = getApplicationContext();
mobileBackend = MobileBackendManager.getManager().getDefaultMobileBackend(mCtx);
mAuthorization = mobileBackend.getAuthorization(AuthType.SSO);

Then you create a thread to handle the authentication call and its callback.

private final Object lock = new Object();
new Thread(new Runnable() {
    @Override
    public void run() {
        mAuthorization.authenticateSSO(mCtx, cookies.isChecked(), new AuthorizationCallback() {
            @Override
            public void onCompletion(ServiceProxyException exception) {
                if (exception != null)
                    Logger.debug(TAG, "Exception " + exception.getMessage());
                else {
                    Logger.debug(TAG, "SSO Auth Succeeded");
                }
                synchronized (lock) {
                    lock.notifyAll();
                }
            }
        });

        synchronized (lock) {
            try {
                lock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}).start();

SSO with a Third-Party Token

First, your app needs to get a token from the third-party token issuer. The way you can obtain the token varies by issuer. For detailed information on obtaining third-party tokens and configuring identity providers in MCS, see Third-Party SAML and JWT Tokens.

Once you have the token, initialize the authorization agent and use the token in your authorization call.

private AuthorizationAgent mAuthorization; 
private MobileBackend mobileBackend; 

Context mCtx = getApplicationContext();
mobileBackend = MobileBackendManager.getManager().getDefaultMobileBackend(mCtx);
mAuthorization = mobileBackend.getAuthorization(AuthType.TOKENAUTH);
mAuthorization.authenticateUsingTokenExchange(mCtx, token, false, mLoginCallback);

Here’s the callback:

AuthorizationCallback mLoginCallback = new AuthorizationCallback() {
    @Override
    public void onCompletion(ServiceProxyException exception) {
        if (exception == null) {
            //log event with Analytics
            mAnalyticsAgent.logEvent("Login with 3rd party token successfully");
            mAnalyticsAgent.flush();
             
            //redirect to another Activity after login
            Intent intent = new Intent(mCtx, ContentActivity.class);
            startActivity(intent);
  
        } else {
            Log.e(TAG, "Exception during token exchange:", exception);
            finish();
        }
    }
};

SSO with a Third-Party Token — Staying Logged In

You can also code the app to keep the user logged in, even when closing and restarting the app.

In the above example, the authenticateUsingTokenExchange() method is called with the third parameter (storeToken) set to false. If you set this parameter to true and the token exchange is successful, the MCS token is stored in a secure store and the user remains logged in until the token expires.

You can then use the loadSSOTokenExchange method on the Authorization object to load the stored token. If a token can’t be retrieved from the secure store, the method returns false.

Here’s some code that tries to load a saved token and, if it fails, restarts the authentication process:

try {
    mAuthorization = MobileBackendManager.getManager().getDefaultMobileBackend(mCtx).getAuthorization();
    if (!mAuthorization.loadSSOTokenExchange(mCtx)) {
        //user not logged in, so need to initiate login
        mAuthorization.authenticateUsingTokenExchange(mCtx, token, true, mLoginCallback);
    }

When you have the token stored in the secure store, it remains associated with the mobile backend that the app originally used. Therefore, if the app is updated to use a different mobile backend (or mobile backend version), you need to clear the saved token and re-authenticate.

mAuthorization.clearSSOTokenExchange(mCtx);
mAuthorization.authenticateUsingTokenExchange(mCtx, token, true, mLoginCallback);

Note:

The default expiration time for a stored token that was obtained through token exchange is 6 hours. You can adjust this time by changing the Security_TokenExchangeTimeoutSecs policy.

HTTP Basic Authentication

The code for handling login with HTTP Basic is nearly the same as the code for OAuth.

First you initialize the authorization agent and set the authentication type to BASIC_AUTH.

private AuthorizationAgent mAuthorization; 
private MobileBackend mobileBackend; 
Context mCtx = getApplicationContext();
mobileBackend = MobileBackendManager.getManager().getDefaultMobileBackend(mCtx);
mAuthorization = mobileBackend.getAuthorization(AuthType.BASIC_AUTH)

Then you use the authenticate method to attempt authentication. The call includes parameters for Android context, user name, password, and a callback that completes the authorization process.

TextView username, password; 
username = (TextView) findViewById(R.id.username);
password = (TextView) findViewById(R.id.password);
String userName = username.getText().toString(); 
String passWord = password.getText().toString();
mAuthorization.authenticate(mCtx, userName, passWord, mLoginCallback); 

Here’s the definition for the callback.

AuthorizationCallback mLoginCallback = new AuthorizationCallback() {
   @Override
   public void onCompletion(ServiceProxyException exception) {
     Log.d(TAG, "OnCompletion Auth Callback");
     if (exception != null) {
       Log.e(TAG, "Exception while receiving the Access Token", exception);
     } else {
   Log.e(TAG, "Authorization successful");
   }
  }
 }

Facebook

For Facebook login, you use classes in the oracle_mobile_android_social library.

First you initialize the authorization agent and set the authentication type to Facebook.

private AuthorizationAgent mAuthorization;
private SocialMobileBackend socialMobileBackend;
Context mCtx = getApplicationContext();
socialMobileBackend = SocialMobileBackendManager.getManager().getDefaultMobileBackend(mCtx);
mAuthorization = socialMobileBackend.getAuthorization(AuthType.Facebook);
mAuthorization.setAuthType(AuthType.Facebook);

Using a CallbackManager object from Facebook’s SDK, initiate authentication.

private CallbackManager callbackManager;
mAuthorization.setup(getApplicationContext(), callback);
callbackManager = mAuthorization.getCallBackManager();
mAuthorization.authenticateSocial(mCtx);

Here’s code you can use for the callback that is passed above.

private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
    @Override
    public void onSuccess(LoginResult loginResult) {
        Log.e(TAG, "facebook login successful.");
    }
    @Override
    public void onCancel() {
    }
    @Override
    public void onError(FacebookException e) {
    }
};

Override the onActivityResult() method to use the callback.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    callbackManager.onActivityResult(requestCode, resultCode, data);

Calling Platform APIs Using the SDK for Android

Once the mobile backend’s configuration info is loaded into the app, you can make calls to SDK classes.

The root class in the Android SDK is the MobileBackendManager. An instance of MobileBackendManager manages one or moreMobileBackend objects. A MobileBackend object is used to manage connectivity, authentication, and other transactions between your application and its associated mobile backend, including calls to platform APIs and any custom APIs you have defined. In turn, a MobileBackend instance manages instances of ServiceProxy. These instances correspond to platform services in MCS (for example, Analytics, Notifications, Sync, and so on).

The MobileBackend instance retrieves the information it needs about each mobile backend (the mobile backend name, version, and ID, as well as authentication information) from the app’s oracle_mobile_cloud_config.xml file.

Here’s an example of how you would use these classes to make calls into the Analytics API to create a new analytics event. The ServiceProxy instance created here manages calls to the Analytics platform API, including the constructing of the HTTP headers with the mobile backend credentials necessary to access the API:

...
byte[] imageBytes = new byte[0];
try {
    Analytics analytics = MobileBackendManager.getManager().getDefaultMobileBackend(this).getServiceProxy(Analytics.class);
    Event customEvent = new Event("App Submission", new Date(), null);
    customEvent.addProperty("Image Attached", new Boolean(imageBytes.length > 0).toString());
    analytics.logEvent(customEvent);
    analytics.flush();
} catch(ServiceProxyException e) {int errorCode = e.getErrorCode();
...
} 

Here’s how you could upload an image using the Storage API:

try {
    Storage storage = MobileBackendManager.getManager().getDefaultMobileBackend(this).getServiceProxy(Storage.class);
    StorageCollection imagesCollection = storage.getStorageCollection("FIF_Images");
    StorageObject imageToUpload = new StorageObject(null, imageBytes, "image/jpeg");
    StorageObject uploadedImage = imagesCollection.post(imageToUpload);
} catch(ServiceProxyException e) {int errorCode = e.getErrorCode();
            ...
}

And here’s how you could retrieve an image using the Storage API:

try {
    Storage storage = MobileBackendManager.getManager().getDefaultMobileBackend(this).getServiceProxy(Storage.class);
    StorageCollection imagesCollection = storage.getStorageCollection("FIF_Images");
    StorageObject image = imagesCollection.get("3x4mp1e-st0r4g3-0bj3ct-k3y");byte[] imageBytes = image.getPayloadBytes();
} catch(ServiceProxyException e) {int errorCode = e.getErrorCode();
 ...
}

For more information on the individual platform APIs, see Platform APIs.

Calling Custom APIs Using the SDK for Android

The SDK provides the CustomHttpResponse class, the GenericCustomCodeClientCallBack interface, and the invokeCustomCodeJSONRequest method in the authorization classes to simplify the calling of custom APIs in MCS. You can call a REST method (GET, PUT, POST, or DELETE) on an endpoint where the request payload is JSON or empty and the response payload is JSON or empty.

You use GenericCustomCodeClientCallBack to create a handler for the response (which is returned in the form of a CustomHttpResponse object.)

Then, to call the custom API, you call invokeCustomCodeJSONRequest(GenericCustomCodeClientCallBack restClientCallback, JSONObject data, String functionName, RestClient.HttpMethod httpMethod) on your Authorization object.

To make a call to a custom API endpoint, you could use something like this:

import org.json.JSONObject;
import oracle.cloud.mobile.customcode.CustomHttpResponse;
import oracle.cloud.mobile.customcode.GenericCustomCodeClientCallBack;
import oracle.cloud.mobile.mobilebackend.MobileBackendManager;
.......
 
final GenericCustomCodeClientCallBack genericCustomCodeClientCallBack = new GenericCustomCodeClientCallBack() {
    @Override
    public void requestCompleted(CustomHttpResponse response, JSONObject data, Exception e) {
        boolean getResponse = (response.getHttpStatus() >=200 && response.getHttpStatus() <300);
                   
        // write any logic based on above response
    }
};
AuthorizationAgent authorization = MobileBackendManager.getManager().getDefaultMobileBackend(mContext).getAuthorization();
            
authorization.authenticate(mContext, "user1", "pass1", successCallback);

........
// after the user successfully authenticates, make a call to the custom API endpoint
authorization.invokeCustomCodeJSONRequest(genericCustomCodeClientCallBack, null, "TaskApi/tasks", RestClient.HttpMethod.GET);

Video: Configuring an Existing Android App to Work with Mobile Cloud

For a demonstration on how to configure an Android app to use mobile backends and call MCS platform APIs, see this video on YouTube channel for the Oracle Mobile Platform: