Skip to Content

Step by Step with the SAP Cloud Platform SDK for Android

Part 8 — Usage

Previous (Remembering Credentials)   Next (Configuration Provider and the Discovery Service)

The usage API enables an application to be instrumented to record details of how the application is being used and includes details of the device. This information is stored in a database on the device and can be uploaded to the SAP Cloud Platform Mobile Services so the details can be viewed and analyzed in aggregate.

The following are some additional sources of documentation on usage.
Client Usage
Client Usage API Reference

The below steps will demonstrate how the app can use the Usage feature to record events, how the data can be uploaded to the server, and how the data can be viewed and placed into a graph.
Enable Usage Policy
Record Events
Download the Usage Report
Visualizing Usage Data

Enable Usage Policy

  1. In Management Cockpit, go to Mobile Applications, Step by Step, Client Policies, Usage Report Policy
  2. Check the checkbox Enable Usage Report Policy
  3. It is possible via the Storage Service to query the Client Usage Policy. This is not covered in this example.

Record Events

  1. Add the following methods to MainActivity.java which will initialize usage, upload any previous events, and record how long the app is in the foreground for.
    @Override
    protected void onStop() {
        super.onStop();
        Log.d(myTag, "onStop");
        try {
            AppUsage.eventEnd("appUsageType", "appDuration",
                    new AppUsageInfo().duration("App has stopped"));
            AppUsage.sessionEnd();
        }
        catch (IllegalStateException e) {
            //this might happen if there was a problem during the initialization of the app
            //and usage was not initialized before the onStop event fires
            Log.d(myTag, "In onStop, and an exception occurred with ending the usage session.");
        }
    }
    
    private void initializeUsage() {
        EncryptionUtil.initialize(getApplicationContext());
        try {
            SettingsParameters sp = new SettingsParameters(serviceURL, appID, deviceID, "1.0");
            AppUsage.initialize(getApplicationContext(), "myUsageStore", sp, EncryptionUtil.getEncryptionKey("sample_alias"));
            uploadUsage();  //upload any previous usage
            AppUsage.sessionStart();
            AppUsage.eventStart("appUsageType", "appDuration",
                    new AppUsageInfo().duration("App has initialized"));
        }
        catch (MalformedURLException e) {
            e.printStackTrace();
        }
        catch (EncryptionError encryptionError) {
            encryptionError.printStackTrace();
        }
        catch (OpenFailureException ex) {
            myLogger.error("Failed to open Usage store.", ex);
        }
    }
    
    public void uploadUsage() {
        AppUsageUploader.UploadListener myUsageUploadListener = new AppUsageUploader.UploadListener() {
            @Override
            public void onSuccess() {
                Log.d(myTag,"Successfully uploaded usage data");
                toastAMessage("Successfully uploaded usage data");
            }
    
            @Override
            public void onError(Throwable throwable) {
                Log.d(myTag,"Encountered error while uploading Message: " + throwable.getMessage());
                toastAMessage("Encountered error while uploading.  Message: " + throwable.getMessage());
            }
    
            @Override
            public void onProgress(int percentage) {
                Log.d(myTag, "Usage upload % " + percentage);
            }
        };
        AppUsageUploader.setListener(myUsageUploadListener);
        AppUsageUploader.upload(myOkHttpClient);
    }
    
  2. Add the following call to the end of the onRegister method in the response.isSuccessful block, below the line that logs “Registration finished”.
    initializeUsage();
  3. Add the following logic inside the setupOfflineOData method in the success block for myOfflineDataProvider.open after the log line for App is ready. This will create usage entries for the time it takes to open the offline store and the time from when the app opened until the app is ready to be used.
    AppUsage.event(
            "timerType",
            "appReadyEventKey",
            4L,
            new AppUsageInfo()
                    .action("App ready to be used")
                    .value(appReadyTimeInSeconds + "")
                    .category("App Metrics"));
    
    AppUsage.event(
            "timerType",
            "timeToOpenOfflineStoreEventKey",
            4L,
            new AppUsageInfo()
                    .action("Time for offline store to open")
                    .value(openOfflineStoreTimeInSeconds + "")
                    .category("App Metrics"));
        
  4. Run the app. Close the app. Open the app.

Download the Usage Report

To view application usage report, go to your management cockpit.

Note, columns can be hidden by selecting them and pressing Cntl 0.

The above shows two runs of the app after it was uninstalled and reinstalled. Notice that the first value of 33 seconds includes the time taken to enter the credentials.
The second value of 6 seconds includes the time to initially create the offline database and populate it with data.
The fifth and sixth values are much shorter as there is no need for the user to enter their credentials the second time the app opens and the offline store opens much quicker after the first time it is opened.

When using the emulator, the database file can be seen at data/data/package_name/databases as shown below.

Visualizing Usage Data

The below steps will generate a graph showing the time taken for the application to open and the time for the offline store to open on two different devices, a Motorola E4 value phone and the Android Emulator.
Different devices behave differently as their hardware is different or may be using different networks.

The following steps can be used to clean up the data to focus on the parts we will be using.

  1. Ctrl + A to select all columns.
    Click on the Home tab, then Format, Autofit Column Width.
  2. In the Name column enter A:C, E:Q, S:Y and press Enter.
    Click on the Home tab, then Format, Hide and Unhide and choose Hide Columns.
  3. Press the Green triangle to select all columns.
    Choose the Data tab.
    Click on Sort and apply the following sort.
  4. Here is the resultant data which shows the length of time it takes until the app is ready to be used and the length of time it took the offline store to be opened.

    Note that the first time the app is opened, the user is prompted to enter their credentials and the offline store is created on the server, populated and downloaded to the device. We will not be using this first time metrics in the following graphs.

  5. Next create average values for the App ready to be used and the Time for the offline store to open.
  6. Select the Device Models and matching average App Ready to be used time and under Insert, click on the bar chart.
  7. Repeat the above step for Time for offline store to open resulting in two bar charts.
  8. Copy the second chart into the first one.
  9. Modify the title to be App Start Up Time.
  10. Provide labels for the series data.
  11. Add a legend.

Previous (Remembering Credentials)   Next (Configuration Provider and the Discovery Service)

To report this post you need to login first.

Be the first to leave a comment

You must be Logged on to comment or reply to a post.

Leave a Reply