copyright | lastupdated | ||
---|---|---|---|
|
2019-02-19 |
{:new_window: target="_blank"} {:shortdesc: .shortdesc} {:screen:.screen} {:codeblock:.codeblock}
{: #instrument-the-application}
The {{site.data.keyword.mobileanalytics_full}} SDKs enable you to instrument your mobile application. {: shortdesc}
{{site.data.keyword.mobileanalytics_short}} enables you to collect the following categories of data, and each requires a different degree of instrumentation:
-
Pre-defined data - This category includes generic usage and device information that applies to all applications. Within this category is device metadata (operating system and device model) and usage data (active users and application sessions) that indicates the volume, frequency, or duration of application use. Pre-defined data is collected automatically after you initialize the {{site.data.keyword.mobileanalytics_short}} SDK in your application.
-
Application log messages - This category enables the developer to add lines of code throughout the application that log custom messages to assist in development and debugging. The developer assigns a severity/verbosity level to each log message and can subsequently filter messages by assigned level or preserve storage space by configuring the application to ignore messages that are at a lower level of a given log level. To collect application log data, you must initialize the {{site.data.keyword.mobileanalytics_short}} SDK within your application, as well as add a line of code for each log message.
-
Custom events - This category includes data that you define yourself and that is specific to your app. This data represents events that occur within your app, such as page views, button taps, or in-app purchases. In addition to initializing the {{site.data.keyword.mobileanalytics_short}} SDK in your app, you must add a line of code for each custom event that you want to track.
Currently SDKs are available for Android, iOS, WatchOS, Cordova and Web.
{: #analytics-clientkey}
Identify your API Key value before you set up the client SDK. The API Key is required for initializing the client SDK.
- Open your {{site.data.keyword.mobileanalytics_short}} service dashboard.
- Expand View Credentials to reveal your API Key value. You will need the API Key value when you initialize the {{site.data.keyword.mobileanalytics_short}} Client SDK.
{: #initalize-ma-sdk}
Initialize your application to enable sending logs to the {{site.data.keyword.mobileanalytics_short}} service.
-
Import the Client SDK.
-
Android
Add the following
import
statements to the beginning of your project file:import com.ibm.mobilefirstplatform.clientsdk.android.core.api.*; import com.ibm.mobilefirstplatform.clientsdk.android.analytics.api.*; import com.ibm.mobilefirstplatform.clientsdk.android.logger.api.*;
{: codeblock}
-
iOS
The Swift SDK is available for iOS and watchOS. Import the
BMSCore
andBMSAnalytics
frameworks by adding the followingimport
statements to the beginning of yourAppDelegate.swift
project file:import BMSCore import BMSAnalytics
{: codeblock}
-
Cordova
Add the Cordova plugin by running the following command from your Cordova application root directory:
cordova plugin add bms-core
{: codeblock}
-
Web
Add the Web plugin by either adding the SDK provided as script to index.html:
<script src="/path/to/bms-clientsdk-web-analytics/bmsanalytics.js"></script>
{: codeblock}
Or, add the Web pluginby using module loader requirejs:
require.config({ 'paths': { 'bmsanalytics': '/path/to/bms-clientsdk-web-analytics/bmsanalytics' } }); require(['bmsanalytics'], function(BMSAnalytics) { BMSAnalytics.send(); }
{: codeblock}
-
-
Initialize the {{site.data.keyword.mobileanalytics_short}} Client SDK in your application.
-
Android
Initialize the {{site.data.keyword.mobileanalytics_short}} Client SDK in your Android application by adding the initialization code in the
onCreate
method of the main activity in your Android application, or in a location that works best for your project.BMSClient.getInstance().initialize(getApplicationContext(), BMSClient.REGION_US_SOUTH); // Make sure that you point to your region
{: codeblock}
You must initialize the
BMSClient
with the bluemixRegion parameter. In the initializer, the bluemixRegion value specifies which {{site.data.keyword.Bluemix_notm}} deployment you are using, for example,BMSClient.REGION_US_SOUTH
andBMSClient.REGION_UK
. -
iOS
First initialize the
BMSClient
class, using the following code. Place the initialization code in theapplication(_:didFinishLaunchingWithOptions:)
method of your application delegate, or in a location that works best for your project.BMSClient.sharedInstance.initialize(bluemixRegion: BMSClient.Region.usSouth) // Make sure that you point to your region
{: codeblock}
You must initialize the
BMSClient
with the bluemixRegion parameter. In the initializer, the bluemixRegion value specifies which {{site.data.keyword.Bluemix_notm}} deployment you are using, for example,BMSClient.Region.usSouth
orBMSClient.Region.unitedKingdom
. -
Cordova
Initialize BMSClient and BMSAnalytics. You will need your API Key value.
BMSClient.initialize(BMSClient.REGION_US_SOUTH); //Make sure you point to your region
{: codeblock}
To use the {{site.data.keyword.mobileanalytics_short}} Client SDK, you must initialize the
BMSClient
with the bluemixRegion parameter. In the initializer, the bluemixRegion value specifies which {{site.data.keyword.Bluemix_notm}} deployment you are using, for example,BMSClient.REGION_US_SOUTH
orBMSClient.REGION_UK
. -
Web
Initialize the Client SDK inside your application code to record usage analytics and application sessions, using your API Key value.
BMSAnalytics.Client.initialize(BMSAnalytics.Client.REGION_US_SOUTH);
{: codeblock}
To use the {{site.data.keyword.mobileanalytics_short}} Client SDK, you must initialize the
BMSAnalytics.Client
with the bluemixRegion parameter. In the initializer, the bluemixRegion value specifies which {{site.data.keyword.Bluemix_notm}} deployment you are using, for example,BMSAnalytics.Client..REGION_UK
orBMSAnalytics.Client..REGION_US_SOUTH
.
-
-
Initialize Analytics by using your application object and giving it your application’s name.
The name that you select for your application (
your_app_name_here
) displays in the {{site.data.keyword.mobileanalytics_short}} console as the application name. The application name is used as a filter to search for application logs in the dashboard. When you use the same application name across platforms (for example, Android and iOS), you can see all logs from that application under the same name, regardless of which platform the logs were sent from.You also need the API Key value.
-
Android
// In this code example, Analytics is configured to record lifecycle events. Analytics.init(getApplication(), "your_app_name_here", apiKey, hasUserContext, collectLocation, Analytics.DeviceEvent.ALL);
{: codeblock}
Note: Set the value for
hasUserContext
to true or false. If false (default value), each device is counted as an active user. TheAnalytics.setUserIdentity("username")
method, which enables you to track the number of users per device who are actively using your application, will not work whenhasUserContext
is false. If true, each use ofAnalytics.setUserIdentity("username")
counts as an active user. There is no default user identity whenhasUserContext
is true, and therefore must be set to populate the active user charts. TheAnalytics.logLocation()
method , which enables the app to send the device location , will work if thecollectLocation
is set true. -
iOS
Analytics.initialize(appName: "your_app_name_here", apiKey: "your_api_key_here", hasUserContext: false, collectLocation: true, deviceEvents: .lifecycle, .network)
{: codeblock}
-
watchOS
Analytics.initialize(appName: "your_app_name_here", apiKey: "your_api_key_here",collectLocation: true, deviceEvents: .network)
{: codeblock}
An optional
deviceEvents
parameter automatically gathers analytics for device-level events.Set the value for
hasUserContext
to true or false. If false (default value), each device is counted as an active user. TheAnalytics.userIdentity = "username"
method, which enables you to track the number of users per device who are actively using your application, will not work whenhasUserContext
is false. IfhasUserContext
is true, each use ofAnalytics.userIdentity = "username"
counts as an active user. There is no default user identity whenhasUserContext
is true, and therefore must be set to populate the active user charts. TheAnalytics.logLocation()
method , which enables the app to send the device location , will work if thecollectLocation
is set true. -
watchOS
You can record device events on WatchOS by using the
Analytics.recordApplicationDidBecomeActive()
andAnalytics.recordApplicationWillResignActive()
methods.Add the following line to the
applicationDidBecomeActive()
method of the ExtensionDelegate class:Analytics.recordApplicationDidBecomeActive()
{: codeblock}
Add the following line to the
applicationWillResignActive()
method of the ExtensionDelegate class:Analytics.recordApplicationWillResignActive()
{: codeblock}
-
Cordova
Analytics.initialize(appName, apiKey, hasUserContext, collectLocation, [BMSAnalytics.ALL])
{: codeblock}
Set the value for
hasUserContext
to true or false. If false (default value), each device is counted as an active user. TheAnalytics.setUserIdentity("username")
method, which enables you to track the number of users per device who are actively using your application, will not work whenhasUserContext
is false. If true, each use ofAnalytics.setUserIdentity("username")
(#android-tracking-users) counts as an active user. There is no default user identity whenhasUserContext
is true, and therefore must be set to populate the active user charts. TheAnalytics.logLocation()
method , which enables the app to send the device location , will work if thecollectLocation
is set true. -
Web
// In this code example, Analytics is configured to record allevents. BMSAnalytics.initialize(appName, apiKey, hasUserContext, BMSAnalytics.DeviceEvent.ALL);
{: codeblock}
Set the value for
hasUserContext
to true or false. If false (default value), each device is counted as an active user. TheBMSAnalytics.setUserIdentity("username")
method, which enables you to track the number of users per device who are actively using your application, will not work whenhasUserContext
is false. If true, each use ofBMSAnalytics.setUserIdentity("username")
counts as an active user. There is no default user identity whenhasUserContext
is true, and therefore must be set to populate the active user charts.
- You have now initialized your application to collect analytics. Next, you can send analytics data to the {{site.data.keyword.mobileanalytics_short}} service.
{: #app-monitoring-gathering-analytics}
You can configure the {{site.data.keyword.mobileanalytics_short}} client SDK to record usage analytics and send the recorded data to the {{site.data.keyword.mobileanalytics_short}} service.
Use the following APIs to start recording and sending usage analytics:
-
Android
// Disable recording of usage analytics (for example, to save disk space) // Recording is enabled by default Analytics.disable(); // Enable recording of usage analytics Analytics.enable(); // Send recorded usage analytics to the Mobile Analytics Service Analytics.send(new ResponseListener() { @Override public void onSuccess(Response response) { // Handle Analytics send success here. } @Override public void onFailure(Response response, Throwable throwable, JSONObject jsonObject) { // Handle Analytics send failure here. } });
{: codeblock}
Sample usage analytics for logging an event:
// Log a custom analytics event JSONObject eventJSONObject = new JSONObject(); eventJSONObject.put("customProperty" , "propertyValue"); Analytics.log(eventJSONObject);
{: codeblock}
-
iOS (Swift)
// Disable recording of usage analytics (for example, to save disk space) // Recording is enabled by default Analytics.isEnabled = false // Enable recording of usage analytics Analytics.isEnabled = true // Send recorded usage analytics to the Mobile Analytics Service Analytics.send(completionHandler: { (response: Response?, error: Error?) in if let response = response { // Handle Analytics send success here. } if let error = error { // Handle Analytics send failure here. } })
{: codeblock}
Sample usage analytics for logging an event:
// Log a custom analytics event let eventObject = ["customProperty": "propertyValue"] Analytics.log(metadata: eventObject)
{: codeblock}
-
Cordova
// Enable usage analytics recording BMSAnalytics.enable(); // Disable usage analytics recording BMSAnalytics.disable(); // Send recorded usage analytics to the {{site.data.keyword.mobileanalytics_short}} Service BMSAnalytics.send( function(response) { console.log('success: ' + response); }, function (err) { console.log('fail: ' + err); });
{: codeblock}
Sample usage analytics for logging an event:
// Log a custom analytics event var eventObject = {"customProperty": "propertyValue"} BMSAnalytics.log(eventObject)
{: codeblock}
When you are developing Cordova applications, use the native API to enable application lifecycle event recording.
-
Web
// Disable recording of usage analytics (for example, to save disk space) // Recording is enabled by default BMSAnalytics.disable(); // Enable recording of usage analytics BMSAnalytics.enable(); // Send recorded usage analytics to the Mobile Analytics Service BMSAnalytics.send().then(function(result) { //Handle Success here }, function(err) { //Handle Failure here });;
{: codeblock}
Sample usage analytics for logging an event:
// Log a custom analytics event var eventObject = {"customProperty": "propertyValue"} BMSAnalytics.log(eventObject)
{: codeblock}
The {{site.data.keyword.mobileanalytics_full}} Client SDK provides a logging framework that is similar to other log frameworks that you might be familiar with, such as java.util.logging
or log4j
. The logging framework supports multiple per-package logger instances, different log levels, capturing of stack traces for an application crash, and more.
You can also configure the logged data to be stored on the device where the application is running and send these device logs to the {{site.data.keyword.mobileanalytics_short}} Service at a later time.
The {{site.data.keyword.mobileanalytics_short}} Client SDK logging framework supports the following log levels, which are listed from least to most verbose, with recommended use guidelines:
FATAL
- Use for unrecoverable crashes or hangs. TheFATAL
level is reserved for logging unrecoverable errors, which appear to users as an application crashERROR
- Use for unexpected exceptions or unexpected network protocol errorsWARN
- Use to log usage warnings that are not considered critical errors, such as usage of deprecated APIs or slow network responseINFO
- Use for reporting initialization events and other data that might be important, but not urgentDEBUG
- Use for reporting debug statements to help developers resolve application defects
{: #log-level-scenario notoc}
When the logger level is configured to FATAL
, the logger captures uncaught exceptions, but does not capture any logs that lead up to the crash event. You can set a more verbose logger level to ensure that logs that might lead to a FATAL
logger entry, such as WARN
and ERROR
, are also captured.
When the logger level is set DEBUG
, you also get Mobile Analytics Client SDK logs, which are included when you send logs.
{: #sample-logger-usage notoc}
Note: Make sure that you have instrumented your application to use the {{site.data.keyword.mobileanalytics_short}} Client SDK before you use the logging framework.
The following code snippets show sample Logger usage:
-
Android
// Configure Logger to save logs to the device so that they // can later be sent to the Mobile Analytics service // Disabled by default; set to true to enable Logger.storeLogs(true); // Change the minimum log level (optional) // The default setting is Logger.LEVEL.DEBUG Logger.setLogLevel(Logger.LEVEL.INFO); // Create two logger instances // You can create multiple log instances to organize your logs Logger logger1 = Logger.getLogger("logger1"); Logger logger2 = Logger.getLogger("logger2"); // Log messages with different levels // Debug message for feature 1 // Info message for feature 2 logger1.debug("debug message"); //the logger1.debug message is not logged because the logLevelFilter is set to Info logger2.info("info message"); // Send logs to the Mobile Analytics Service Logger.send(new ResponseListener() { @Override public void onSuccess(Response response) { // Handle Logger send success here. } @Override public void onFailure(Response response, Throwable throwable, JSONObject jsonObject) { // Handle Logger send failure here. } });
{: codeblock}
-
iOS (Swift)
// Configure Logger to save logs to the device so that they // can later be sent to the Mobile Analytics service // Disabled by default; set to true to enable Logger.isLogStorageEnabled = true // Change the minimum log level (optional) // The default setting is LogLevel.debug Logger.logLevelFilter = LogLevel.info // Create two logger instances // You can create multiple log instances to organize your logs let logger1 = Logger.logger(name: "feature1Logger") let logger2 = Logger.logger(name: "feature2Logger") // Log messages with different levels logger1.debug(message: "debug message for feature 1") // The logger1.debug message is not logged because the // logLevelFilter is set to info logger2.info(message: "info message for feature 2") // Send logs to the Mobile Analytics Service Logger.send(completionHandler: { (response: Response?, error: Error?) in if let response = response { logger.debug(message: "Status code: \(response.statusCode)") logger.debug(message: "Response: \(response.responseText)") } if let error = error { logger.error(message: "Error: \(error)") } })
{: codeblock}
Tip: For privacy concerns, you can disable Logger output for applications that are built in release mode. By default, the Logger class prints logs to the Xcode console. In the build settings for your target, add a
-D RELEASE_BUILD
flag to the Other Swift Flags section of the release build configuration. -
Cordova
// Enable persisting logs BMSLogger.storeLogs(true); // Set the minimum log level to be printed and persisted BMSLogger.setLogLevel(BMSLogger.INFO); var logger1 = BMSLogger.getLogger("logger1"); var logger2 = BMSLogger.getLogger("logger2"); // Log messages with different levels logger1.debug ("debug message"); logger2.info ("info message"); // Send persisted logs to the {{site.data.keyword.mobileanalytics_short}} Service BMSLogger.send(); BMSAnalytics.send();
{: codeblock}
-
Web
// Enable persisting logs BMSAnalytics.Logger.storeLogs(true); // Set the minimum log level to be printed and persisted // log levels in descending verbose level trace,debug,log,info,warn,error,fatal,analytics BMSAnalytics.Logger.setLogLevel('error'); // Log messages with different levels BMSAnalytics.Logger.debug ("debug message"); BMSAnalytics.Logger.info ("info message"); // Send persisted logs to the {{site.data.keyword.mobileanalytics_short}} Service BMSAnalytics.Logger.send(); BMSAnalytics.send().then(function(result) { //Handle Success here }, function(err) { //Handle Failure here });;
{: codeblock}
{: #location-logging}
Location of the mobile device may be logged from the app through this api provided.
Analytics.logLocation();
This api enables the app to send its location as latitude , longitude to the server in between appsession . Other than this explicit calls to location-logging api sdk sends device location for every App-Session , both for initial AppSession context and userswitch AppSession (i.e. switch of user between a app session ) context. The location api needs to be enabled in the initialization of sdk as mentioned earlier.
Note: To call this location logging api set collectLocation
parameter to true in sdk initialization as shown below.
Analytics.initialize(appName, apiKey, hasUserContext, collectLocation, [BMSAnalytics.ALL])
{: #network-requests}
You can configure the {{site.data.keyword.mobileanalytics_short}} Client SDK to make a network request. Be sure that you have already initialized BMSClient
and BMSAnalytics
and imported the Client SDKs.
{: #report-crash-analytics}
You can see application crash data by sending analytics and log information to {{site.data.keyword.mobileanalytics_short}}.
The Analytics.send()
method populates the Crash Overview and Crashes tables on the Crashes page. Charts in this section are enabled by using the initialization and sending process for analytics; no special configuration is necessary.
The Logger.send()
method populates the the Crash Summary and Crash Details tables on the Troubleshooting page. You must enable your application to store and send logs to populate the charts in this section, by adding an additional statement in your application code:
-
Android
Logger.storeLogs(true);
See the Android sample logger usage.
-
iOS
Logger.isLogStorageEnabled = true
See the iOS sample logger usage.
-
Cordova
BMSLogger.storeLogs(true);
See the Cordova sample logger usage.
-
Web
BMSAnalytics.Logger.storeLogs(true);
{: #trackingusers}
If your application can recognize unique users on a device, you can optionally track how many users are actively using your application by passing the user name of the active user to {{site.data.keyword.mobileanalytics_short}}.
Enable user tracking by initializing {{site.data.keyword.mobileanalytics_short}} with hasUserContext=true
. Otherwise, {{site.data.keyword.mobileanalytics_short}} captures only one user per device.
-
Android
Add the following code to track when the user logs in:
Analytics.setUserIdentity("username");
{: codeblock}
-
iOS (Swift)
Add the following code to track when the user logs in:
Analytics.userIdentity = "username"
{: codeblock}
-
Cordova
Add the following code to track when the user logs in:
BMSAnalytics.setUserIdentity("username");
{: codeblock}
-
Web
Add the following code to track when the user logs in:
BMSAnalytics.setUserIdentity("username");
{: codeblock}
{: #In-App}
In-App Feedback Analysis enables users and testers to provide rich contextual feedback to app owners. App owners get real time feedback from its users based on app usage. Developers implement changes based on real time insights.
Invoke the below API to instrument your mobile app to enter the feedback-mode.
-
Android
ImageButton feedback =(ImageButton)findViewById(R.id.Feedback); feedback.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Analytics.triggerFeedbackMode(); } });
{: codeblock}
{: #what-to-do-next notoc}
You can now go to the {{site.data.keyword.mobileanalytics_short}} Console to see usage analytics, such as new devices and total devices using your application. You can also monitor your application by setting alerts and monitoring app crashes.
{: #rellinks notoc}
{: #api notoc}
- REST API
{:new_window}