Chapter 1. Tealeaf installation and implementation in an Android application. IBM Android SDK
Tealeaf Android SDK is a software development kit that enables you to capture user interface and application events from your Android-enabled devices. The SDK allows you to collect data on how users interact with your application and use this information to improve your user experience, optimize your app performance, and troubleshoot any issues that may arise.
Advertisement
Advertisement
Chapter 1. Tealeaf installation and implementation in an
Android application
You add the Tealeaf
®
SDK to your application so that the Android SDK can capture user interface and application events. There are two ways to install the Tealeaf
SDK in your Android application.
Supported Frameworks
The installation and implementation instructions in this guide apply to the step-based version of JSON messaging from this client framework.
The step-based version of JSON messaging from this client framework was introduced in Release 8.5.
For Release 8.5 and later, IBM Tealeaf continues to support the legacy method of submitting data from the client frameworks, which resulted in submitted data being split into individual hits in the Windows pipeline.
In a future release, the hit-splitting method of processing data that is submitted from client frameworks is likely to be deprecated.
The installation and implementation instructions for the legacy version are similar but require additional configuration in the Windows pipeline.
Eclipse Tealeaf plug-in for Android development
The Eclipse Tealeaf plug-in installs the Tealeaf SDK into your Eclipse workspace and includes basic configuration. You download the plug-in and install the plug-in with the Eclipse Install new software option. The plug-in installs custom widgets in your Eclipse workspace. These widgets can be used in any application in that workspace.
If you do not have a custom Application class in your application, the plug-in creates and extends one for you. If you create a custom Application class after you install the plug-in, you:
1.
Create and extend your custom Application class
2.
Modify AndroidManifest.xml file to use your custom Application class
You manually configure properties, including application-specific URLs, and
Android Activity class extension.
Tealeaf SDK for Android development
You manually install and configure the Tealeaf SDK. You download the Tealeaf package and you:
1.
Move files to the proper locations in your application
2.
Configure properties, including application-specific URLs
3.
Extend Application and Activity classes
© Copyright IBM Corp. 1999, 2015
1
Client Framework versions supported in this documentation
The installation and implementation instructions in this guide apply to the step-based version of JSON messaging from this client framework.
The step-based version of JSON messaging from this client framework was introduced in Release 8.5.
For Release 8.5 and later, IBM Tealeaf continues to support the legacy method of submitting data from the client frameworks, which resulted in submitted data being split into individual hits in the Windows pipeline.
Note:
In a future release, the hit-splitting method of processing data that is submitted from client frameworks is likely to be deprecated.
The installation and implementation instructions for the legacy version are similar but require additional configuration in the Windows pipeline.
Install the Tealeaf SDK for Android development in your application
You add the Tealeaf SDK to your application so that the Android SDK can capture user interface and application events. You manually install and configure the
Tealeaf SDK in each application .
Tealeaf SDK for Android development
You manually install and configure the Tealeaf SDK. You download the Tealeaf installation package and you:
1.
Move files to the proper locations in your application
2.
Configure properties, including application-specific URLs
3.
Extend Application and Activity classes
Tealeaf package contents
A single file contains the Android SDK and its software components.
IBM Tealeaf Android SDK is delivered in the IBM Tealeaf Android SDK 8.8 - iOS
Logging Framework for Windows within the IBM Passport Advantage Online.
The package contains the following software components.
v KillSwitch . Code to implement the kill switch traffic manager for different server technologies.
– ASPX:
- killswitch.aspx: Page with logic.
- web.config: Configuration file that is used by the page.
– JSP:
- killswitch.jsp: Page with logic.
- config.properties: Configuration file that is used by the page.
– PHP
- killswitch.php: Page with logic.
- config.ini: Configuration file that is used by the page.
v PipelineAgents
- JSON parser for Android logging framework v UICAndroid :
2
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
– uicandroid.jar: Android library JAR file that contains the Android SDK.
– TLFConfigurableItems.properties: Configuration file.
v SampleCode
: Contains the following versions of a sample Android application.
– UICSP_Clean: An Android application without IBM Tealeaf Android SDK integrated.
– UICSP_ManualLog: An Android application with IBM Tealeaf Android SDK integrated
– UICSP_ManualLog_ServerSessionID: An Android application with IBM Tealeaf
Android SDK integrated by using a session ID provided from a web application.
See "Sample Code" in the IBM Tealeaf Android SDK Guide.
v AndroidEclipsePlugin - An Eclipse Plug-in to assist with Tealeaf Integration.
– tealeaf.plugin.android.site-1.0.0-SNAPSHOT.zip The Plug-in archive to be added to your Eclipse IDE.
– tealeafandroidsdk.jar - Android Library JAR file that contains pre-instrumented Tealeaf widgets.
Tealeaf sample application
You deploy the sample application that is provided by IBM Tealeaf to test the capabilities and measure the effects of the Android SDK.
Instead of integrating the Android SDK with your application in development, you deploy the sample application and complete any necessary configuration steps on the remainder of this page to begin to capture mobile app data into your instance of IBM Tealeaf.
See Chapter 3, “Sample applications,” on page 101.
Android development environment requirements
To develop Android applications with the Android SDK, follow these system and software requirements.
Minimum requirements
Develop Android applications with a minimum API Level 8, which is Android 2.2
(Froyo).
Consult the Google Android Dev Center for the latest Android technical documentation and tools.
IBM Tealeaf client frameworks do not support forwarding of application data to third-party systems. Application data must be forwarded to the server that hosts the native application.
Supported operating systems
Tealeaf supports these versions of the Windows, Mac, and Linux operating systems: v Windows XP (32-bit), Vista (32- or 64-bit), or Windows 7 (32- or 64-bit) v Mac OS X 10.5.8 or later (x86 only) v
Linux (tested on Ubuntu Linux, Lucid Lynx)
– GNU C Library (glibc) 2.7 or later is required.
Chapter 1. Tealeaf installation and implementation in an Android application
3
– On Ubuntu Linux, version 8.04 or later is required.
– 64-bit distributions must be able to run 32-bit applications. For information about how to add support for 32-bit applications, see the Ubuntu Linux installation notes.
Eclipse platforms
Tealeaf supports these Eclipse platforms: v Froyo 2.2
v Galileo 3.5
v Helios 3.6
v Indigo 3.7
v Juno 4.2
v
Kepler 4.3
v
Tealeaf uses the Eclipse JDT plug-in (included in most Eclipse IDE packages).
For information on the Eclipse versions supported by the Android Development
Tools, check the Eclipse web sitehttp://www.eclipse.org/.
Eclipse packages
Several types of Eclipse packages are available for each platform. For developing
Android applications, install one of these packages.
v Eclipse IDE for Java
™
Developers
– Java version 1.6.
– Java version 1.7 can be used in compatibility mode.
v Eclipse Classic v Eclipse IDE for Java EE Developers
– JDK 5 or JDK 6 (JRE alone is not sufficient).
– Android Development Tools plug-in
– Not compatible with GNU Compiler for Java (gcj)
Tealeaf impact on Android device resources
In benchmark tests, the Android SDK has the following effects on resources of the visitor's device.
v
2-3% more memory consumption v Minimal effect on battery life
Android project changes
After you acquire IBM Tealeaf Android SDK, complete the following steps to install the Android SDK libraries into an Android application project.
Your Eclipse project must include the frameworks that follow. Testing of the
Android SDK involved Android 2.2 to 4.3.3.
Install the UICAndroid.jar
You install the uicandroid.jar in to your Android application to make the capture functions available in your application. There are two ways to install the uicandroid.jar
, either in Eclipse or in another build environment.
4
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
Using Eclipse to install the uicandroid.jar:
Follow these instructions to use the Eclipse integrated development environment to install the uicandroid.jar in an Android application.
1.
In Eclipse, open the Android application to be instrumented.
2.
Place uicandroid.jar into the lib folder.
3.
Right-click uicandroid.jar and select Build Path.
4.
Click Add on Build Path.
Installation of the uicandroid.jar in another environment:
In integrated development environments other than Eclipse, you add the
UICAndroid.jar
into the build path of the application you want to instrument.
Installation of TLFConfigurableItems.properties
To install the TLFConfigurableItems.properties file, place it in the assets folder of the Android application.
Auto-instrumentation not supported
Android enables the use of a one handler at a time for any object. As a result, the
Android SDK cannot auto-instrument objects.
You must apply instrumentation as part of your application development.
Configure Tealeaf properties
You configure several items for your app in Tealeaf, including how screen layouts are logged, Target page location, kill switch location, and whether gestures will be logged.
TLFConfigurableItems.properties
Everything that you configure is in the TLFConfigurableItems.properties file. The
TLFConfigurableItems.properties
file is in the Install Package.
Configurable properties
There are many properties that you can configure in Tealeaf. At the minimum, you must configure: v Whether to display logcat messages.
v
The Target page URL.
v Enable/disable the kill switch URL v The kill switch URL.
v How screen layouts are logged.
v The logging level.
For information to the other properties that you can configure, go to <link to reference topic that I don't have access to right now>.
Whether to display logcat messages
Whether you see logcat messages is set with the DisplayLogging property.
Chapter 1. Tealeaf installation and implementation in an Android application
5
Set Target URL
All events that are captured are sent in JSON format to a Target page. The Target page acknowledges the receipt of the JSON message and forwards the client-side events to Tealeaf. The person that sets up Tealeaf on the server creates the Target page. The Target page is set with the PostMessageUrl property.
Enable and set kill switch
The Kill Switch is used to control logging. When the kill switch is enabled, it must have a URL to check before the framework initializes. When the page is reachable, the framework initializes. If the page is not reachable, because of network problems or because you disabled it on your server, the framework does not initialize. The kill switch URL is set by the person who sets up Tealeaf on the server. The kill switch is enabled with the KillSwitchEnabled property. The kill switch URL is set with theKillSwitchUrl property.
How screen layouts are logged
Tealeaf can log screen images as base64 or as MD5 checksum with png or jpg images. Set GetImageDataOnScreenLayout to YES to capture base 64 data. Set
GetImageDataOnScreenLayout to NO to log MD5 checksum and png or jpg images.
This option creates smaller payloads in production and is the recommended setting.
Set logging level
You set the logging level based on where your project is in the development cycle.
You can set the level high for development and testing and then lower the logging level for production. The logging level is set with the LoggingLevel property.
Auto-instrumentation
Android enables the use of one handler at a time for any object. As a result, auto-instrumentation is not supported in Tealeaf. You must apply instrumentation as part of your application development.
Configuring Tealeaf properties for your application
You configure Tealeaf to use specific URLS for logging events and to control message flow, set how screen layouts are logged, modify logging levels.
All of the configuration in this task involves modifying settings in the
TLFConfigurableItems.properties
file in the Assets folder of your Eclipse project.
1.
In your Eclipse, open the TLFConfigurableItems.plist file.
2.
Set the DisplayLogging to False.
3.
Set the PostMessageUrl to the URL of the target page for your app.
4.
Set the KillSwitchEnabled to True.
5.
Set the KillSwitchUrl to the URL for the kill switch for your app.
6.
Set the GetImageDataOnScreenLayout to False.
7.
Set the LoggingLevel to an appropriate level for development, testing, or production.
8.
Save and exit the TLFConfigurableItems.properties file.
6
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
Extended Android classes
You extend Android classes to provide logging for components in your application.
You can extend the classes with the IBM Tealeaf extended classes or you can extend the classes manually. If you install the Tealeaf SDK, you must extend the
Application and Activity classes. When you install the Eclipse Tealeaf plug-in, you must extend only the Activity class. How you extend the classes depends on whether you have custom Application or Activity classes.
Application class
You extend the Activity class to automatically capture points the lifecycle of a native Android application page. Tealeaf listens to these events: v onLowMemory - disable the library when you get a LowMemory warning v onCreate - initialize the library when the application starts v onTerminate - clean up the library when the application is terminated
How you extend the Application class depends on whether you have a custom activity class for your application. If you: v Do not have a custom Application class for your application, use the IBM
Tealeaf class UIApplication. You do this only if you are not using the Eclipse
Tealeaf plug-in. The plug-in automatically extends the Application class with the
Tealeaf UICApplication class.
v Have a custom Activity class for your application, modify your custom
Application class to point to the Tealeaf UICApplication class.
Application class and the Eclipse Tealeaf plug-in
After you install the Eclipse Tealeaf plug-in, if you decide to use a custom
Application class in your application, you need to change the Application class automatically added by the plug-in:
1.
Create the custom Application class.
2.
Modify AndroidManifest.xml file for the application and change the application class name to the name of Application class you created.
Activity class
You extend the Activity class to automatically capture points the lifecycle of a native Android application page. Tealeaf listens to these events: v onPause - what happens when the application goes to the background v onResume - what happens when the application goes to the foreground v onDestroy - what happens when the activity is no longer in memory and gets garbage collected
How you extend the Activity class depends on whether you have a custom activity class for your application. If you: v Do not have a custom Activity class for your application, use the Tealeaf
UIActivity class.
v Have a custom Activity class for your application, modify your custom Activity class to point to the Tealeaf UICActivity class.
Chapter 1. Tealeaf installation and implementation in an Android application
7
Extending the Application class with the Tealeaf UICApplication class
If you do not have a custom Application class, you can use the IBM Tealeaf
UICApplication class to extend the Application class. The application file manages the lifecycle of an Android application. IBM Tealeaf manages the library by listening to onLowMemory to disable library if you get a warning, onTerminate to clean up library, and onCreate to initialize the library.
1.
Open the existing Java file that extends from application class. If this file does not exist, you must create it and have it listen to the complete lifecycle of an
Android application to control library and log information needed. You must also change the file to extend from com.tl.uic.app.UICApplication instead of android.app.Application
.
2.
Add these imports: a.
import com.tl.uic.Tealeaf; b.
import com.tl.uic.app.UICApplication;
3.
In onCreate() method, add Tealeaf.enable() that initializes capture of user actions in the application.
4.
Adjust AndroidManifest.xml to indicate application class. For example, if your application class is named MyApplication, you can add
⌂android:name=".MyApplication" in <application> node.
5.
Add the following permissions in AndroidManifest.xml.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.SET_DEBUG_APP" />
This example shows the lines that you add to the AdroidManifest.xml file: import com.tl.uic.Tealeaf; import com.tl.uic.app.UICApplication; public class MyApplication extends UICApplication {
@Override public void onCreate() { super.onCreate();
Tealeaf.enable();
}
}
Extending the Activity class with the Tealeaf UICActivity class
The activity file manages the lifecycle of a page in a native Android application similar to what a page does in a web application. IBM Tealeaf listens to the following events onPause, which happen when application goes to the background, onResume , which happens when application goes to foreground, and onDestroy when activity is no longer in memory and gets garbage collected.
On each activity files that you want to log, extend it using UICActivity. Using
UICActivity extends the base Activity from the Android framework. UICActivity adds some functionality that is required by the IBM Tealeaf Logging Framework library to enable and disable asynchronous tasks, and to perform screen captures of the device after creation.
To avoid capturing potentially private data, the Android SDK takes screen captures as soon as the image was rendered on the device. As a result, no user-defined fields are populated in any captured screen image.
Android does not support capture of pop-up windows.
8
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
For hybrid applications, screen captures might be missing or out of order due to timing issues.
The method in this task enables automatic capture of screen captures from the client application. If you do not enable this item through UICActivity, you can manually capture screen captures through the Logging Framework. See "Reference" in the IBM Tealeaf Android SDK Guide.
The value for the black background color can be replaced by any color constant to set the color of the background of your screen captures.
1.
Open the existing Java file that extends from android.app.Activity class, and change it to extend from com.tl.uic.app.UICActivity instead of android.app.Activity
.
2.
Add these imports: a.
Import com.tl.uic.Tealeaf; b.
Import com.tl.uic.app.UICApplication;
3.
In the onCreate() method, add: a.
Add this.setTakeSnapshotAfterCreate(true); //To enable automatic screen shots .
b.
Add setLogicalPageName("LoginPage") //Recommended to identify page.
c.
Add setImageBackground(-16777216) //To set to black background of screenshot because the screen capture background is transparent.
This example shows the lines that you add to the file that extends the Activity class: import com.tl.uic.app.UICActivity; public class LoginActivity extends UICActivity {
@Override public void onCreate(Bundle savedInstanceState) { this.setTakeSnapshotAfterCreate(true); //To enable automatic screen shots setLogicalPageName("LoginPage") //Recommended to identify page setImageBackground(-16777216) screenshot
//To set to back background of super.onCreate(savedInstanceState);
Extending your custom Application class to point to the Tealeaf
UICApplication class
If you have a custom Application class in your application, point your custom class to the Tealeaf UICApplication class. The application file manages the lifecycle of an
Android application. IBM Tealeaf manages the library by listening to onLowMemory to disable library if you get a warning, onTerminate to clean up library, and onCreate to initialize the library. .
1.
Open the existing Java file that extends from the android.app.Application
class. If this file does not exist, you must create it and have it listen to the complete lifecycle of an Android application to control library and log information needed.
2.
Add this import: import com.tl.uic.Tealeaf;
3.
In onCreate(): a.
Add Tealeaf tealeaf = new Tealeaf(this);, which initializes the IBM
Tealeaf library with a reference to application instrumented.
b.
Add Tealeaf.enable(); that initializes capture of user actions in the application.
4.
In onLowMemory():
Chapter 1. Tealeaf installation and implementation in an Android application
9
a.
Add Tealeaf.onLowMemory(); before super so it can adjust the library due to low memory.
5.
In onTerminate(): a.
Add Tealeaf.disable(); before super so it can disable the library.
6.
Adjust AndroidManifest.xml to indicate application class. For example, if your application class is named MyApplication, you can add
⌂android:name=".MyApplication" in <application> node.
7.
Add these permissions to AndroidManifest.xml.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.SET_DEBUG_APP" />
This example shows the lines you add to the file that extends the Application class: import android.app.Application; import com.tl.uic.Tealeaf; public class MyApplication extends Application {
@Override public void onCreate() { super.onCreate();
Tealeaf tealeaf = new Tealeaf(this);
Tealeaf.enable();
}
@Override public void onLowMemory() {
Tealeaf.onLowMemory(); super.onLowMemory();
}
}
@Override public void onTerminate() {
Tealeaf.disable(); super.onTerminate();
}
Extending your custom Activity class to point to the Tealeaf
UICActivity class
If you have a custom Activity class, extend it to point to the Tealeaf UICActivity class. The activity file manages the lifecycle of a page in a native Android application similar to what a page does in a web application. IBM Tealeaf listens to the following events onPause, which happen when application goes to the background, onResume, which happens when application goes to foreground, and onDestroy when activity is no longer in memory and gets garbage collected.
Each activity needs a logical page name that helps indicate what activity is being displayed. If no logical page name is given, IBM Tealeaf recommends using class name that gives some indication what activity is being displayed.
1.
Open the existing Java file that extends from android.app.Activity class, and change it to extend from com.tl.uic.app.UICActivity instead of android.app.Activity
.
2.
Add this import: a.
Import com.tl.uic.Tealeaf;
3.
Add the logical page name to the class:
10
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
private String logicalPageName; public final String getLogicalPageName() { if ((this.logicalPageName == null) ||
(this.logicalPageName.equals(""))) { this.logicalPageName = this.getClass().getName().substring(this.getClass()
.getName().lastIndexOf(".") + 1);
} return this.logicalPageName;
}
4.
In the onPause() method, add: a.
Add Tealeaf.onPause(this, getLogicalPageName());
5.
In the onResume() method, add: a.
Add Tealeaf.onResume(this, getLogicalPageName());
6.
In the onDestroy() method, add: a.
Add Tealeaf.onDestroy(this, getLogicalPageName());
This example shows the lines that you add to the file that extends your custom
Activity class: import com.tl.uic.Tealeaf; public class BaseActivity extends Activity { private String logicalPageName;
/**
* Logical page name of the Activity.
*
* @return Logical page name of the Activity.
*/ public final String getLogicalPageName() { if ((this.logicalPageName == null) ||
(this.logicalPageName.equals(""))) { this.logicalPageName = this.getClass().getName().substring(this.getClass().
getName().lastIndexOf(".") + 1);
} return this.logicalPageName;
}
/**
* Logical page name of the Activity.
*
* @param logicalPageName
*
*/
Logical page name of the Activity.
public final void setLogicalPageName(final String logicalPageName) { this.logicalPageName = logicalPageName;
} protected void onPause() {
Tealeaf.onPause(this, getLogicalPageName()); super.onPause();
} protected void onResume() {
Tealeaf.onResume(this, getLogicalPageName()); super.onResume();
} protected void onDestroy() {
Chapter 1. Tealeaf installation and implementation in an Android application
11
}
}
Tealeaf.onDestroy(this, getLogicalPageName()); super.onDestroy();
Implement Tealeaf
After you install Tealeaf, you complete several tasks to implement Tealeaf functions in your application. These tasks involve modifying your application to capture controls, events, and screen views.
Implementation tasks
After you install the SDK, you must complete more tasks to implement the SDK.
All of these tasks must be done for both the Tealeaf SDK and Eclipse Tealeaf plug-in for Tealeaf to work. All of these tasks are manual.
This table lists and describes the tasks that you complete to implement Tealeaf in your application:
Task
Log Screen Layout for Android Mobile App
Replay
Tealeaf SDK ONLY
Integration for Apache Cordova, PhoneGap, and IBM Worklight
® applications that use
Android classes without IBM Tealeaf classes
Implementing screenViews
Target page configuration
Data privacy
Description
Configure logging screen layout to use JSON data not screen captures. Includes configuring logical pages names, alert dialogs, and keyboard events.
Integrate Cordova, PhoneGap, and IBM
Worklight applications in your application.
Includes extending the Application class for onCreate, onLowMemory, onTerminate methods and onPause, on'Resume, and onDestroy methods for Cordova.
Implementing screenViews as segments for pages in which the state or context can be switched without rerendering the page.
Set up the target page that acknowledges that events are captured.
Specify the fields that are blocked or masked during capture.
Configure how session IDs are generated.
Configuring sessionization for Android applications on the client
Network traffic that is used in application contains requests only
Configure requests in Android application
Uses non-IBM Tealeaf session ID
Hybrid application
Tealeaf supports network traffic that is used in applications that contain requests only.
Configure Tealeaf to put session identifiers in cookies.
Configure your generated session IDs to be used when sessions are enabled or new sessions started.
Configure your application to log request activity if you have a WebView in your application.
12
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
Log screen layout for mobile app session replay
IBM Tealeaf has functions to log screen layouts for screenviews of native mobile app sessions. You can replay a mobile app session in cxImpact Browser Based
Replay as you would an HTML web session instead of viewing the mobile app session as a series of screen captures.
The screen layouts of the native mobile app sessions are captured in IBM Tealeaf
JSON format. The screen layouts are then sent back to replay server. The replay server uses a template engine, which interprets the JSON into HTML format. You can then replay the screen layout from the native mobile app session as HTML pages in cxImpact Browser Based Replay.
There are several advantages to using JSON data to replay mobile app session over screen captures.
v
Reduce bandwidth. Screen captures for each screenview generate relatively large image data. It not only consumes large amounts of wireless and cellular bandwidth, but it also consumes more memory inside the device. It also impacts the app performance.
v Mask sensitive information. You cannot mask sensitive information in a screen capture. When you use JSON data to replay mobile app sessions, you can mask
EditTexts by adding View IDs to the MaskIdList attribute in
TLFConfigurableItems.properties
.
v Draw user interactions (UI events) onto the HTML pages that are created from the JSON data.
For more information on mobile ap session replay templates, see "Native app session replay customization" in the IBM Tealeaf CX Configuration Manual.
TLFConfigurableItems.properties
changes
For native app session replay to be activated, you must set
LogViewLayoutOnScreenTransition to true. If you do not, the library functions as it currently does.
#Capture native layout
LogViewLayoutOnScreenTransition=true
During predeployment, you must perform all the replay cases to collect all the images with GetImageDataOnScreenLayout set to true. This creates a large payload sent to server that contains base64 images that are used for replay. When the application is ready to be deployed to Play Store, GetImageDataOnScreenLayout must be changed to false.
#Current only done on ImageView
GetImageDataOnScreenLayout=true
Understand your activity
In Android, an Activity can be considered a page, which is displayed on mobile device. By default, you should record an activity that is displayed.
For more information, see http://developer.android.com/training/basics/activitylifecycle/starting.html.
You can record an activity that is displayed, by placing the following information in the OnCreate method.
Chapter 1. Tealeaf installation and implementation in an Android application
13
// this will indicate logical page name.
Tealeaf.logScreenview(activity, "Name", ScreenviewType.LOAD);
// this will get layout of page after it being created.
Tealeaf.logScreenLayoutOnCreate(activity, "Name");
If you need to log a layout, you can use the following.
Tealeaf.logScreenLayout(activity, "Name", delayInMS);
Replaying AlertDialogs
You need to know when an alert dialog is displayed so it can be captured correctly.
OnShowListener is correct location to use for this.
// This will capture background and alert when it is displayed.
Tealeaf.logScreenLayoutSetOnShowListener(activity, dialog);
If there is already a OnShowListener, follow this example.
// This is placed inside OnShowListener:
Tealeaf.logScreenLayout(activity, dialog);
To capture an alert dialog event, follow this example.
public void onClick(DialogInterface dialog, int id) {
Tealeaf.logDialogEvent(dialog, id);
Replaying keyboard events
Android does not provide an event to understand when a soft keyboard appears and disappears. Follow this example to make the necessary adjustments to
TextView based controls.
public static void addFocusAndRegister(TextView textView, Activity activity) { textView.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) {
InputMethodManager imm = (InputMethodManager) v.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(v, InputMethodManager.SHOW_FORCED);
KeyboardView keyboardView = new KeyboardView(v.getContext()
.getApplicationContext(), null);
Tealeaf.logEvent(keyboardView , Tealeaf.TLF_UI_KEYBOARD_
DID_SHOW_NOTIFICATION);
Tealeaf.logEvent(v, Tealeaf.TLF_ON_FOCUS_CHANGE_IN);
} else {
Tealeaf.logEvent(v, com.tl.uic.Tealeaf.TLF_ON_FOCUS_CHANGE_OUT);
InputMethodManager imm = (InputMethodManager) v.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
KeyboardView keyboardView = new KeyboardView(v.getContext()
.getApplicationContext(), null);
Tealeaf.logEvent(keyboardView , Tealeaf.TLF_UI_KEYBOARD
_DID_HIDE_NOTIFICATION);
}
}
});
Tealeaf.registerFormField(textView, activity);
}
EditText et = (EditText) findViewById(R.id.editText1); addFocusAndRegister(et, this);
14
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
For more information, review ControlsActivity3.java in the Sample Code project,
UICAndroidControlsAppdarkHolo
.
Supported controls
IBM Tealeaf replays controls that are extended from the following controls. For each control, IBM Tealeaf fills in the tlType value in the json object that is sent back to the server.
ToggleButton and Switch
Uses switch template
RadioGroup and RadioButton
Uses radioButton template
CheckBox
Uses checkBox template
Button
Uses button template
Scroller, HorizontalScrollView, ScrollView
Uses scroll template
AbsSeekBar
Uses slider template
ProgressBar
Uses progressSpinner or progressBar template
AbsSpinner
Uses selectList template
EditText
Uses label template
TextView
Uses switch template
ImageView
Uses image template
FrameLayout, LinearLayout, ViewStub, View
Uses canvas template
AbsListView
Uses grid template
AlertDialog
Uses alert template
TabWidget
Uses tabBar template
TabHost
Uses tabContainer template
Integrate Tealeaf and IBM MobileFirst Platform Foundation
IBM MobileFirst Platform Foundation is IBM's Mobile First Platform for developing both Hybrid and Native Apps on multiple mobile platforms. For logging activities on your application, you might want to integrate the Tealeaf library inside of a IBM MobileFirst Platform Foundation "Hybrid" application. IBM
Chapter 1. Tealeaf installation and implementation in an Android application
15
MobileFirst Platform Foundation provides an Eclipse plug-in called "IBM
MobileFirst Platform Foundation Developer Studio" to help Developers create
Mobile Apps more productively.
Development environment
To integrate Tealeaf with IBM MobileFirst Platform Foundation, you need these files: v Eclipse IDE for Java EE Developers (Kepler): http://www.eclipse.org/ downloads/packages/release/Kepler/SR2 v IBM MobileFirst Platform Foundation Developer Studio version 6.1. You need the compressed file iws_update_site_wde.6.1.0.2.zip
v IBM MobileFirst Platform Foundation Developer Studio version 6.2. You need the compressed file iws_eclipse_6.2.0.zip. Unless you need IBM MobileFirst
Platform Foundation 6.1, you should integrate with Worklight 6.2.
You must also:
1.
Install the IBM MobileFirst Platform Foundation Developer Studio inside
Eclipse following the instructions in the Worklight documentation.
2.
Install the Android ADT plug-in in your Eclipse instance.
3.
Register the Tealeaf/Application in the AndroidManifest.xml
IBM MobileFirst Platform Foundation high-level single project
Within IBM MobileFirst Platform Foundation, you can create and manage Mobile project artifacts in a single, high-level project called "IBM MobileFirst Platform
Foundation Project". Artifacts include server-side adapters, multiple android projects, and multiple iOS projects All artifacts in the single, high-level project have access to the same resources..
Differences between IBM MobileFirst Platform Foundation 6.1 and IBM
MobileFirst Platform Foundation 6.2
In 6.1, IBM MobileFirst Platform Foundation and Tealeaf are packaged together. IN
IBM MobileFirst Platform Foundation 6.2 they are no longer packaged together.
For 6.2, you must do additional steps to integrate the two products.
Modify Tealeaf and IBM MobileFirst Platform Foundation classes
Part of integrating Tealeaf and IBM MobileFirst Platform Foundation 6.2 is extending and modfying Tealeaf and IBM MobileFirst Platform Foundation classes.
This table lists the classes and methods that you modify and shows examples of the modifications:
Method or class
Tealeaf UICApplication class
Example
package com.HelloWorklight; import com.tl.uic.Tealeaf; import com.tl.uic.app.UICApplication; public class TealeafApplication extends UICApplication {
@Override public void onCreate() { super.onCreate();
Tealeaf.enable();
}
}
16
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
Method or class
IBM MobileFirst Platform Foundation
CordovaActivity class
Tealeaf onResume, onPause, and onDestroy methods
Customize the onInitWebFrameworkComplete method
Example
public class HelloWorklight extends
CordovaActivity implements
WLInitWebFrameworkListener {
@Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState);
//Tealeaf Integration super.init();
// Tealeaf Integration: Log Screenview for this activity
Tealeaf.logScreenview(this, this.getClass().getName(),
ScreenviewType.LOAD);
// Tealeaf Integration: Add bridge for
Tealeaf data to be sent back appView.addJavascriptInterface(new
JavaScriptInterface(this.
getBaseContext()), "tlBridge");
WL.createInstance(this);
WL.getInstance().showSplashScreen(this);
WL.getInstance().initializeWebFramework
(getApplicationContext(), this);
}
//Tealeaf Integration public void onResume() {
// Handle Tealeaf during onResume event
Tealeaf.onResume(this, this.getClass()
.getName()); super.onResume();
} public void onPause() {
// Handle Tealeaf during onPause event
Tealeaf.onPause(this, this.getClass()
.getName()); super.onPause();
} public void onDestroy() {
// Handle Tealeaf during onResume event
Tealeaf.onDestroy(this, this.getClass()
.getName()); super.onDestroy();
} publicvoid onInitWebFrameworkComplete(
WLInitWebFrameworkResult result){ if (result.getStatusCode() ==
WLInitWebFrameworkResult.SUCCESS) { super.loadUrl(WL.getInstance()
.getMainHtmlFilePath());
//Tealeaf Integration
Tealeaf.logScreenLayout(this, this.getClass().getName(),
2000);
} else {
(result);
}
} handleWebFrameworkInitFailure
Chapter 1. Tealeaf installation and implementation in an Android application
17
Process
To integrate Tealeaf and IBM MobileFirst Platform Foundation, you:
1.
Create a high-level IBM MobileFirst Platform Foundation project called "IBM
MobileFirst Platform Foundation Project"
2.
Add the Tealeaf SDK to the high-level "IBM MobileFirst Platform Foundation
Project".
3.
Create an Android project under the high-level "IBM MobileFirst Platform
Foundation Project"
4.
Modify activity and UIC classes for Tealeaf (for integration with IBM
MobileFirst Platform Foundation 6.2 only)
5.
Activate Tealeaf in the JavaScript layer.
6.
Update to Tealeaf 9.0.0.13, if you have not already. (applies to IBM MobileFirst
Platform Foundation 6.1 only)
Creating and configuring the high-level Worklight project:
You can manage your Tealeaf and Worklight integration with the high-level
Worklight Project. To integrate Tealeaf and Worklight 6.1, you create the high-level
Worklight project, add the Tealeaf SDK to the project, and activate Tealeaf in the
JavaScript layer.
In this task, you work in the Eclipse environment. You modify your application and add libraries to the project.
1.
Create the high-level Worklight project: a.
In Eclipse, select New > Project > Worklight Project.
b.
Enter the name of the project, for example Worklight Project and select
Hybrid Application
.
c.
Enter the name of the Hybrid Application that you are creating. For example, HelloWorklight. The high-level project is created and a Hybrid application that is called HelloWorklight is in the apps folder.
2.
Activate the Tealeaf SDK on the high-level Worklight project: a.
Open the file apps/HelloWorklight/application-descriptor.xml.
b.
Select Optional Features > Add > IBM Tealeaf SDK
3.
Create an Android project under the high-level Worklight Project: a.
Right click on the HelloWorklight folder under Apps.
b.
Select New > Worklight Environment.
c.
Select Android phones and tablets.
4.
Optional: For integrating Tealeaf and Worklight 6.2 only: Modify the classes and methods required for Tealeaf and Worklight integration: a.
Extend the Tealeaf UICApplication class b.
Modify the Worklight CordovaActivity class c.
Modify the Tealeaf onPause, onResume, and onDestroy methods.
5.
Activate Tealeaf in the JavaScript layer: a.
Copy the defaultconfiguration.js file from the Tealeaf 9.0.0.13 install package to the Worklight project apps/HelloWorklight/andoid/js folder.
b.
Modify the index.html file and add <script src="js/ defaultconfiguration.js"</script> before the break in the <body> element.
c.
Modify the defaultconfiguration.js file and set the DOM Capture options that you want to use:
18
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
replay: {
// DOM Capture configuration domCapture: { enabled: true,
// Filter object for matching rules is similar to the Privacy configuration
// It accepts a mandatory "event" followed by one or more optional targets
// as well as an optional delay after which to take the DOM snapshot.
triggers: [
{ event: "load"
}
],
// DOM Capture options options: { captureFrames: true, // Should child frames/iframes be captured removeScripts: true // Should script tags be removed from the captured snaphot
}
}
} d.
If DOM Capture does not fire on load, set DOM Capture to fire from your application by adding this code to your Native Android application for the screenview that you want to capture: if (TLT === undefined) { console.log(’TLT is undefined!’);
} else { if (TLT.logScreenviewLoad === undefined) { console.log(’Could not invoke TLT.logScreenviewLoad API!’);
} else {
TLT.logScreenviewLoad("root"); console.log(’logScreenviewLoad:’);
} if (TLT.logDOMCapture === undefined) { console.log(’Could not invoke TLT.logDOMCapture API!’);
} else { dcid = TLT.logDOMCapture(window.document, {}); console.log(’logDOMCapture:’ + dcid);
}
}
6.
Right click the apps/HelloWorklight folder and select Run As > Build All
Environments
7.
Optional: If you are a version of Tealeaf older than 9.0.0.13. upgrade to Tealeaf
3.0.0.13: a.
Copy the uicandroid.jar file from the Tealeaf 9.0.0.13 install package into
HelloWorklightHelloWorklightAndroid/libs folder.
b.
Copy the TLFConfigurableItems.properties file from the Tealeaf 9.0.0.13
install package into the HelloWorklightHelloWorklightAndroid/assets folder
Integrate Apache Cordova and PhoneGap applications using
Android classes without Tealeaf classes
This method has developers add code snippets that help the IBM Tealeaf capture library.
android.app.Application file code changes:
The application file manages the lifecycle of an Android application. IBM Tealeaf manages the library by listening to onLowMemory to disable library if you get a
Chapter 1. Tealeaf installation and implementation in an Android application
19
warning, onTerminate to clean up library, and onCreate to initialize the library. IBM
Tealeaf recommends this as a best practice.
Locating the file that extends from android.app.Application
This file most likely will not exist so you must create it and add it to listen to the complete lifecycle of an Android application to control library and log information needed.
1.
Create application class from android.app.Application and add the following.
If application class is found, then continue to the next steps.
2.
Open the existing Java file that extends from android.app.Application class.
3.
Add the following imports.
a.
import com.tl.uic.Tealeaf; b.
import com.tl.uic.app.UICApplication;
4.
In onCreate(): a.
Add Tealeaf tealeaf = new Tealeaf(this);, which initializes the Tealeaf library with a reference to application instrumented.
b.
Add Tealeaf.enable(); that initializes capture of user actions in the application.
5.
In onLowMemory(): a.
Add Tealeaf.onLowMemory(); before super so it can adjust library due to low memory.
6.
In onTerminate():: a.
Add Tealeaf.disable(); before super so it can disable library.
7.
Adjust AndroidManifest.xml to indicate application class, by adding android:name=".MyApplication" .
Example in Application class
import android.app.Application; import com.tl.uic.Tealeaf; public class MyApplication extends Application {
@Override public void onCreate() { super.onCreate();
Tealeaf tealeaf = new Tealeaf(this);
Tealeaf.enable();
}
@Override public void onLowMemory() {
Tealeaf.onLowMemory(); super.onLowMemory();
}
}
@Override public void onTerminate() {
Tealeaf.disable(); super.onTerminate();
}
20
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
Example in AndroidManifest.xml
<application android:label="@string/app_name" android:debuggable="true" android:icon="@drawable/icon" android:name=".TLWorklightTealeafApplication" >
Locating the file that extends from org.apache.cordova.DroidGap:
The file extends from Activity class, which manages the lifecycle of a page in a native Android application similar to what a page does in a web application.
IBM Tealeaf listens to the following events onPause, which happen when application goes to the background, onResume, which happens when application goes to foreground, and onDestroy when activity is no longer in memory and gets garbage collected.
1.
Open the existing Java file that extends from android.app.Activity.
2.
Add these imports.
a.
import com.tl.uic.Tealeaf; b.
import com.tl.uic.app.UICApplication; c.
import com.tl.uic.model.ScreenviewType;
3.
Each activity needs a logical page name that helps indicate what activity is currently being displayed. If no logical page name is given, IBM Tealeaf recommends to use class name that gives some indication what activity is being display. Add this code to the class: private String logicalPageName = "MainPage";
4.
In the onPause() method, add Tealeaf.onPause(this, logicalPageName);.
5.
In the onResume() method, add Tealeaf.onResume(this, logicalPageName);.
6.
In the onDestroy() method, add Tealeaf.onDestroy(this, logicalPageName);.
7.
In the onCreate() method, after super.onCreate( add a.
Tealeaf.logScreenview(this, logicalPageName, ScreenviewType.LOAD); b.
new JavaScriptInterface(this.getContext(),
Tealeaf.getPropertyName(webviewObject).getId()), "tlBridge"
Implementing screenViews
For pages in which the state or context can be switched without re-rendering the page, IBM Tealeaf segments the data between states by using a screenView object.
For example, if a page contains multiple tabs, each of which represents a different stage in a checkout process, you instrument each tab in the page as a distinct screenView.
To implement a screenView for a page, complete the following steps.
1.
If you are extending from UICActivity, set a logicalPageName to indicate the use of the activity. Otherwise, logicalPageName is set to the name of the class of the activity.
2.
If the prior step is not complete, call Tealeaf.logScreenview and pass the logicalPageName . You must also indicate if the page being loaded and unloaded is optional. For example:
Tealeaf.logScreenview(activity, logicalPageName, ScreenviewType.LOAD);
Tealeaf.logScreenview(activity, logicalPageName, ScreenviewType.UNLOAD);
Chapter 1. Tealeaf installation and implementation in an Android application
21
Basic configuration
You must set up a target page on your web server.
See “Quick start for server configuration” on page 88.
Set the target page's address in the TLFConfigurableItems.properties
configuration file under the key PostMessageUrl.
See "Configuration File" in the IBM Tealeaf Android SDK Guide.
Data privacy
IBM Tealeaf provides mechanisms for masking or blocking sensitive customer information, such as credit card numbers, from being transmitted and captured by
IBM Tealeaf. Through the Android SDK, you can specify the fields that need to be blocked or masked in your web application.
When applied, data privacy ensures that these data elements are never transmitted to IBM Tealeaf.
Note:
Due to changes in how client framework data is submitted to IBM Tealeaf for capture, the best method for masking or blocking sensitive data is to apply the filtering through the capturing client framework. While other IBM Tealeaf features to manage data privacy can be deployed, they are not easy to implement on the new format of data captured from the client frameworks. IBM Tealeaf recommends using the methods referenced below.
v See "Configuration File" in the IBM Tealeaf Android SDK Guide.
v For more information about handling sensitive data in general, see "Managing
Data Privacy in Tealeaf CX" in the IBM Tealeaf CX Installation Manual.
Configuring sessionization for Android applications on the client
The Android SDK auto-generates a session ID if one is not provided. This session
ID is used to identify the session on the IBM Tealeaf server.
IBM Tealeaf injects cookies to create session in the IBM Tealeaf system.
Note:
When an Android native or hybrid application is placed into background, the library flushes the collected data and sleeps, instead of disabling it. This happens unless the session expired due to the session timeout property. The timeout property is indicated with SessionTimeout in
TLFConfigurableItems.properties
. The default value for this property is 30 minutes. After a 30-minute timeout, a new session identifier is created.
There are two ways to configure sessionization; either through TLTSID provide by
IBM Tealeaf, or through customer session ID, called JSESSIONID. Both methods function as a unique session identifier within the Android SDK environment for
IBM Tealeaf to track on customer sessions. CookieParam can be set to use customer session ID or JSESSIONID.
The following is a typical setting in TLFConfigurableItems.properties using customer session ID.
#Sessionization settings on customer cookies
CookieUrl = http://www.sample.com
CookieDomain = .sample.com
CookiePath = /
22
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
CookieParam = JSESSIONID
CookieExpires = false
SessionTimeout=30
SessoinTimeoutKillSwitch=false
In this example, the cookie expires 30 minutes from current time. When the session timeout occurs, Android SDK retrieves the new cookie from your application server and posts the rest of request to application server using this new acquired cookie in request header. PCA groups all the used JSESSIONIDs into one single session even though the JSESSIONID was consistently changing. When using cookies generated from customer application server, SessoinTimeoutKillSwitch can be set to true or false. Setting the SessoinTimeoutKillSwitch to false means the session timeout user does not go to recheck on KillSwitchUrl to see if it is responding.
Network traffic used in application contains requests only:
Android SDK uses cookies to add values to the TLFConfigurableItems.properties
file.
Uses session ID generated by IBM Tealeaf Android SDK
Android SDK uses cookies to add the following values in
TLFConfigurableItems.properties
.
v CookieUrl is for url of site that is posted and getting cookie to sessionize on.
v CookieParam is the parameter that has a session id.
v CookiePath is the path of the cookie.
v CookieDomain is the domain that the cookie belongs to.
v CookieSecure is to add a secure cookie that can only be posted to an https url that has a valid certificate.
v CookieExpiresFormat can have the date format of ASCTIME, RFC1036, or
RFC1123, which will have an expiration date of current time + session timeout indicated in the variable below.
v SessionTimeout is session timeout is in minutes. When this value expires a new session id is created.
An example follows.
#Sessionization settings
CookieUrl=http://m.ibm.com
CookieParam=TLTSID
CookiePath=/
CookieDomain=.ibm.com
#Whether you want to create a secure cookie which can only be sent using a https url in PostMessageUrl.
CookieSecure=false
#Valid date formats: ASCTIME, RFC1036, RFC1123
CookieExpiresFormat=ASCTIME
#When post is sent, expiration of cookie will be current time + session timeout
#Session timeout is in minutes
SessionTimeout=30
Note:
It is important to first call your server to get first cookie to sessionize on, which is automatically obtained when you enable the kill switch URL on the application. This is used to aggregate all the data on CX Passive Capture
Application capture.
Chapter 1. Tealeaf installation and implementation in an Android application
23
Configure requests in Android application
IBM Tealeaf needs all the requests to have the session id to be placed in the cookies of the request. This enables the IBM Tealeaf system to collect all the resources together in a single session.
If you are using org.apache.http.impl.client.DefaultHttpClient, you can use com.tl.uic.http.TLDefaultHttpClient
, which adds the appropriate session id in the cookie of the request. If you decide not use the IBM Tealeaf extended class, then you must add the following code to the following classes.
Extend org.apache.http.impl.client.DefaultHTTPClient:
If you do not use the IBM Tealeaf extended TLDefaultHttpClient class, you must add the following code to the following classes.
import org.apache.http.conn.ClientConnectionManager; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpParams;
/**
* @author ohernandez
*
*/ public class TLDefaultHttpClient extends DefaultHttpClient {
/**
*
*/ public TLDefaultHttpClient() { super(); this.init(null);
}
/**
* @param params Http parameters.
*/ public TLDefaultHttpClient(final HttpParams params) { super(params); this.init(null);
}
/**
* @param params Http parameters.
* @param sessionId Tealeaf session id.
*/ public TLDefaultHttpClient(final HttpParams params, final String sessionId) { super(params); this.init(sessionId);
}
/**
* @param conman ClientConnectionManager.
* @param params Http parameters.
*/ public TLDefaultHttpClient(final ClientConnectionManager conman, final HttpParams params) { super(conman, params); this.init(null);
}
/**
* @param sessionId Tealeaf session id.
*/ private void init(final String sessionId) { final TLHttpRequestInterceptor tlHttpRequestInterceptor =
24
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
new TLHttpRequestInterceptor(sessionId); this.addRequestInterceptor(tlHttpRequestInterceptor); this.addResponseInterceptor(new TLHttpResponseInterceptor
(tlHttpRequestInterceptor));
}
}
Extend org.apache.http.HttpRequestInterceptor:
This class is used to inject session id as a cookie and additional headers that the
IBM Tealeaf system uses.
import java.io.IOException; import java.util.Map.Entry; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.protocol.HttpContext; import android.webkit.CookieManager; import com.tl.uic.Tealeaf; import com.tl.uic.util.LogInternal;
/**
* @author ohernandez
*/ public class TLHttpRequestInterceptor implements HttpRequestInterceptor { private String url; private final String sessionId;
/**
* Constructor.
*/ public TLHttpRequestInterceptor() { super(); this.sessionId = null;
}
/**
* Constructor.
* @param sessionId Tealeaf session id.
*/ public TLHttpRequestInterceptor(final String sessionId) { this.sessionId = sessionId;
}
/**
* Get url of the request.
* @return Url of the request.
*/ public final String getUrl() { return url;
}
/**
* Url of the request.
* @param url Url of the request.
*/ public final void setUrl(final String url) { this.url = url;
}
/**
* {@inheritDoc}
*/
Chapter 1. Tealeaf installation and implementation in an Android application
25
public final void process(final HttpRequest request, final
HttpContext context) throws HttpException, IOException { try { this.url = request.getRequestLine().getUri(); if (!request.containsHeader(Tealeaf.TLF_HEADER)) { request.addHeader(Tealeaf.TLF_HEADER, "device (Android) Lib/"
+ Tealeaf.getLibraryVersion());
} if (!request.containsHeader(Tealeaf.TLF_PROPERTY_HEADER)) { request.addHeader(Tealeaf.TLF_PROPERTY_HEADER,
Tealeaf.getHttpXTealeafProperty());
} if (Tealeaf.getAdditionalHeaders() != null) { for (final EntryString,<String> entry :
Tealeaf.getAdditionalHeaders().entrySet()) { request.addHeader(entry.getKey(), entry.getValue());
}
} final StringBuffer cookies = new StringBuffer(Tealeaf.
getTLCookie(this.sessionId)); if (this.getUrl() != null) { final String extistingCookies = CookieManager.getInstance().
getCookie(this.getUrl()); if (extistingCookies != null) { cookies.append(’;’); cookies.append(extistingCookies);
}
}
}catch (final Exception e) {
Tealeaf.logException(e);
} request.addHeader("Cookie", cookies.toString());
LogInternal.log("Session cookie:" + cookies.toString());
}
}
Extend org.apache.http.HttpResponseInterceptor:
This class is used to get information to fill out a IBM Tealeaf connection object.
import java.io.IOException; import java.util.Date; import org.apache.http.HttpException; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.protocol.HttpContext; import com.tl.uic.TLFCache; import com.tl.uic.Tealeaf; import com.tl.uic.util.LogInternal;
/**
* @author ohernandez
*
*/ public class TLHttpResponseInterceptor implements HttpResponseInterceptor { private final TLHttpRequestInterceptor tlHttpRequestInterceptor; private final Date startTime; private final long initTime;
/**
26
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
public TLHttpResponseInterceptor(final TLHttpRequestInterceptor tlHttpRequestInterceptor) { this.tlHttpRequestInterceptor = tlHttpRequestInterceptor; this.startTime = new Date(); this.initTime = TLFCache.timestampFromSession();
}
* Constructor.
*
* @param tlHttpRequestInterceptor TLHttpRequestInterceptor used.
*/
/**
* {@inheritDoc}
*/ public final void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { try { final Date endTime = new Date(); final Date startLoad = new Date(); final long loadTime = (new Date()).getTime() - startLoad.getTime(); final long responseTime = endTime.getTime() - this.startTime.getTime();
Tealeaf.logConnection(this.tlHttpRequestInterceptor.getUrl(), response, this.initTime, loadTime, responseTime);
} catch (final Exception e) {
LogInternal.logException(e);
}
}
}
Uses non IBM Tealeaf session ID
You must get your generated session ID and use it when you enable or start a new session in Android SDK.
// If enabling of Android Logging Framework use
Tealeaf.enable();
Tealeaf.enable("your session id");
// If Android Logging Framework is enabled and a new session is to be created use
Tealeaf.startSession();
Tealeaf.startSession("your session id");
Android application gestures
You can capture gestures that the users make on your Android application. Several types of gestures are captured.
Configuration
For any Activity class that you want Gesture logging, you edit
TLFConfigurableItems.properties
file and set the SetGestureDetector property to true
.
Touch event methods
You add your variables to one of these methods: v onTouchEvent - use this method if your activity is not using a customized gesture view.
v dispatchTouchEvent - use this method if your activity is using a customized gesture view.
If your application uses a customized gesture view, onTouchEvent does not detect the gestures because they are already captured by the customized gesture view. If you are using a customized gesture view, you must use dispatchTouchEvent.
Chapter 1. Tealeaf installation and implementation in an Android application
27
You can use either the onTouchEvent or the dispatchTouchEvent. If you use both, the gestures are captured twice.
Gesture events captured:
Gestures that are used to select items in an application or to adjust views in the application are captured by Tealeaf.
Tap gestures
This table lists and describes the tap gestures that are captured from web and mobile apps.
Note:
The arrows that illustrate the direction of a swipe or pinch gesture are not supported by the Internet Explorer browser.
Table 1. Tap gestures.
Gesture name Description Image displayed in Replay
Tap This gesture is a one-finger gesture.
For a tap gesture, one-finger taps and lifts from the screen in 1 location.
Tap and Hold This gesture is a one-finger gesture.
For a Tap and Hold gesture, one-finger presses and stays on the screen until information is displayed or an action occurs.
Note:
The response to a Tap and Hold gesture can vary from one application to another. For example, a Tap and Hold gesture might display an information bubble, magnify content under the finger, or present the user with a context menu.
Double tap This gesture is a one-finger gesture.
For a double tap gesture, one-finger taps twice in close succession in 1 location of the screen.
Swipe gestures
This table lists and describes the swipe gestures that are captured from web and mobile apps:
28
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
Table 2. Swipe gestures
Gesture name Description
Swipe vertically
Swipe horizontally
This gesture is a one-finger gesture.
For a swipe vertically gesture, one-finger:
1.
taps and holds in 1 location of screen,
2.
continues to engage screen while it moves up or down
3.
lifts from the screen in different location.
Note:
The initial tap becomes lighter in color, while the destination is highlighted by a darker color
This gesture is a one-finger gesture.
For a swipe horizontally gesture, one-finger:
1.
taps and holds in 1 location of screen,
2.
continues to engage screen while it moves left or right
3.
lifts from the screen in different location.
Note:
The initial tap becomes lighter in color, while the destination is highlighted by a darker color
Image displayed in Replay
Resize gestures
This table lists and describes the resize gestures that are captured from web and mobile apps:
Note:
See the IBM Tealeaf Customer Experience 9.0.1 Release Notes for information about a known limitation for handling some iOS pinch gestures.
Table 3. Resize gestures
Gesture name Description
Pinch open Sometimes referred to as a spread gesture, this is a two-finger gesture.
Image displayed in Replay
Pinch close
For a pinch open gesture, 2 fingers:
1.
tap and hold in 1 location of the screen,
2.
maintain contact with the screen while the fingers move apart from each other in any direction,
3.
lift from the screen at a new location.
This gesture is a two-finger gesture.
Note:
Accompanying arrows indicate the direction
(open or close) of the pinch
For a pinch close resize gesture, 2 fingers:
1.
tap and hold in 1 location on the screen,
2.
maintain contact with the screen while the fingers move toward each other,
3.
lift from the screen at a new location.
Note:
Accompanying arrows indicate the direction
(open or close) of the pinch
Chapter 1. Tealeaf installation and implementation in an Android application
29
Unresponsive gesture events captured
Unresponsive gestures are gestures that do not respond when a user tries to select items in an application or tries to adjust views in the application. Like other gesture events, unresponsive gestures are captured by Tealeaf.
Unresponsive gestures are displayed graphically in BBR as orange outlined icons accompanied by a circled "X" . The circled "X" denotes that the gesture was unresponsive. For example, if a double tap gesture did not yield a response in the mobile application, then at replay time that gesture is displayed with the following icon in BBR:
The following table lists the unresponsive gestures that are captured from web and mobile apps and shows the images that are displayed in BBR:
Table 4. Unresponsive gestures and icons
Unresponsive Gesture
Tap gestures
Image displayed in Replay
Unresponsive tap
Unresponsive double tap
Unresponsive tap and hold
Swipe gestures
30
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
Table 4. Unresponsive gestures and icons (continued)
Unresponsive Gesture
Tap gestures
Swipe vertically
Image displayed in Replay
Swipe horizontally
Note:
Accompanying arrows indicate the direction of the swipe.
Resize gestures
Pinch open
Note:
Accompanying arrows indicate the direction of the swipe.
Pinch close
Note:
Accompanying arrows indicate the direction of the pinch.
Note:
Accompanying arrows indicate the direction of the pinch.
Instrumenting your application for Android gestures:
You can enable your application to capture gestures that the user makes on your application. To enable gestures for an Activity class, you modify the Activity class.
Chapter 1. Tealeaf installation and implementation in an Android application
31
For example, you modify the MainActivity.java file and call the
Tealeaf.dispatchTouchEvent method inside dispatchTouchEvent or onTouchEvent method.
To use the Android gestures module, you must the Android Support Library android-support-v4.jar
together with Tealeaf SDK uicandroid.jar. The android-support-v4.jar
is distributed within Android SDK. Download and install the Android Support Library from the Android Support Library site. The installation installs the android-support-v4.jar at ${your Android SDK location}/extras/android/support/v4/android-support-v4.ja
r
1.
Open the MainActivity.java file for your application.
2.
Override either the dispatchTouchEvent or the onTouchEvent method, depending on how you are using gestures in your application:
IF your application is...
using a customized gesture view not using a customized gesture view
THEN...
Override the dispatchTouchEvent publc boolean dispatchTouchEvent
( MotionEvent e) {
}
Tealeaf.dispatchTouchEvent(this, e); return super.dispatchTouchEvent(e);
Override the onTouchEvent publc boolean onTouchEvent
( MotionEvent e) {
Tealeaf.dispatchTouchEvent(this, e); return super.onTouchEvent(e);
}
This example shows the code snippets that are added in this task for an application that does not use a customized gesture view: mport com.tl.uic.Tealeaf; import com.tl.uic.app.UICActivity; import android.os.Bundle; import android.view.MotionEvent; public class MainActivity extends UICActivity{
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
Tealeaf.logScreenLayout(this, this.getLogicalPageName(), 1000);
}
} public boolean dispatchTouchEvent( MotionEvent e) {
Tealeaf.dispatchTouchEvent(this,e); return super.dispatchTouchEvent(e);
}
Modifying the TLFConfiguratbleItems.properties file for gestures:
After you define the variables for gestures in your Activity class, you enable gesture capture by modifying the TLFConfiguratableItems.properties file.
1.
Edit the TLFConfiguratableItems.properties file.
32
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
2.
Set SetGestureDetector to true.
3.
Save and exit the TLFConfiguratableItems.properties file.
Log exceptions
Exceptions are the way that a system or framework communicates to the application that something is wrong. Tealeaf provides two mechanisms to log exceptions. You can manually log exceptions by using the logException API, or
Tealeaf SDK will automatically log uncaught exceptions. The exception information can be used for analytics.
Automatically log exceptions
When your application throws an uncaught exception, Tealeaf Android SDK records the stack trace and state of the device at the time the exception was thrown. Tealeaf Android SDK sends the crash information to your target servers for processing.
Manually log exceptions
In the Android SDK, you modify your catch block to report caught exceptions to the target server for processing. When you modify your catch block, you get the full stack trace and same device information that Tealeaf collects for fatal crashes.
This table shows the method that is used to log exceptions and describes the parameters that are used in the method:
Method
public static Boolean logException(final
Throwable exception, final
HashMap<String, String> data,
final Boolean unhandled)
Parameters
Where: v @param exception - the exception to be logged.
v @param data - the value to be given to event.
v
@param unhandled - whether the exception is unhandled.
v @return - whether exception was logged.
Example
In this example, you have a method that causes an exception: public void clientMethod1( ) {
}
You add an @try , @catch, and the Tealeaf.logException(e, data, false) method to handle the exception: public void clientMethod1( ) { try { int[] array = new int[1]; int i = array[2]; // Index out of bound exception
}
}
} Catch (Exception e) {
HashMap<String, String> data = new HashMap<String, String>(); data.put("extraMessage", "custom value1");
Tealeaf.logException(e, data, false);
Chapter 1. Tealeaf installation and implementation in an Android application
33
Logging exceptions:
Use the examples in this task as a guide to adding exception logging to your application.
1.
Determine the method for which you want to log exceptions. For example, you have a method: public void clientMethod1( ) {
}
2.
Optional: Add the exception method to the method for which you want to log the exceptions.
Add @try , @catch, and the Tealeaf.logException(e, data, false) method to handle the exception: public void clientMethod1( ) { try { int[] array = new int[1]; int i = array[2]; // Index out of bound exception
}
} Catch (Exception e) {
HashMap<String, String> data = new HashMap<String, String>();
}
Tealeaf.logException(e, data, false);
Android application geolocation
You can log geolocation information for the users of your applications. You can configure automatic geolocation logging when the application starts or you can use
APIs to log geolocation information at specific places in your application. Replay and reporting of geolocation data is not available currently.
Automatic logging
You configure automatic logging with the TLFConfigurableItems.properties file and the manifest file.
To give permission to the device to log geolocation data, add this line
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" > to the android manifest file. For example:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.SET_DEBUG_APP" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
There are three configurable items you can set in the
TLFConfigurableItems.properties
:
Property
LogLocationEnabled
LogLocationTries
Description
Use this property to enable geolocation logging. Values are: v True - logging is enabled v False - logging is not enabled
Use this property to set the number of times the device tries to get the geolocation information when the device's signal is weak.
34
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
Property
LogLocationTimeout
Description
Use this property to set the amount of time between retries for the device to get the geolocation information when the device's signal is weak.
For example, when the device signal is weak you want the device to try 3 times to get the geolocation signal and for the device to wait 30 seconds between retries, you set the configurable items to these values:
#Auto Geolocation logging enabled or not
LogLocationEnabled=true
LogLocationTries=3
LogLocationTimeout=30
APIs
There are three APIs you can use to manually enable geolocation information logging in your application: v public static Boolean logGeolocation() - Use this API at a specific point in your application to log geolocation only at that point.
v public static GeoLocation logGeolocation(final Boolean getGeolocation) -
Use this API at a specific point in your application to return a geolocation object that contains latitude, longitude, and accuracy values.
v public static Boolean logGeolocation(final int logLevel) - Use this API at a specific point in your application to log geolocation information based on log level.
Logging geolocation information in your application automatically:
Before you begin this task you need to know: v The number of times you want the application to try to get the geolocation information when the signal is weak.
v The amount of time, in seconds, that you want the application to wait before again trying to get the geolocation information.
1.
In your application in Eclipse, open the TLFConfigurableItems.properties file.
a.
Set LogLocationEnabled to true.
b.
Set LogLocationTries to the number of times you want the application to try log the geolocation information.
c.
Set LogLocationTimeout to the number of seconds that the device should retry when the signal is weak.
d.
Save and exit the file.
2.
In your application in Eclipse, open the AndroidManifest.xml file.
a.
Add this line <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" > to the file.
b.
Save and exit the file.
Hybrid applications
An application is considered to be hybrid if it contains a WebView in the Android application.
If you use a WebView, you must use UICWebView to log request activity in the
WebView. UICWebView extends the base WebView from the Android Framework,
Chapter 1. Tealeaf installation and implementation in an Android application
35
which inserts the IBM Tealeaf header with the current session ID for sessionization.
If you decide not to use UICWebView, then you need to extend a Webview to add sessionization.
See "UICWebView Class" in the IBM Tealeaf Android SDK Guide.
Extend android.webkit.WebView:
This sample code shows how the base Android WebView is extended with
UICWebView .
/*******************************************************************************
* Licensed Materials - Property of IBM
* (C) Copyright IBM Corp. 2015
* US Government Users Restricted Rights - Use, duplication or disclosure
* restricted by GSA ADP Schedule Contract with IBM Corp.
******************************************************************************/ package com.tl.uic.webkit; import java.util.Date; import java.util.Map; import org.apache.http.HttpResponse; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.util.AttributeSet; import android.webkit.WebView; import com.tl.uic.TLFCache; import com.tl.uic.Tealeaf; import com.tl.uic.javascript.JavaScriptInterface; import com.tl.uic.model.PropertyName;
/**
* @author ohernandezltmac
*/ public class UICWebView extends WebView { private Date endLoad; private Date startLoad; private String url; private HttpResponse httpResponse; private Date initTime; private long responseTime; private long connectionInitFromSession; private PropertyName webViewId;
/**
* @param context Android context.
*/ public UICWebView(final Context context) { super(context); init();
}
/**
* @param context Android context.
* @param attrs an AttributeSet passed to our parent.
*/ public UICWebView(final Context context, final AttributeSet attrs) { super(context, attrs); init();
}
/**
36
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
public UICWebView(final Context context, final AttributeSet attrs, final int defStyle) { super(context, attrs, defStyle); init();
}
* @param context Android context.
* @param attrs an AttributeSet passed to our parent.
* @param defStyle the default style resource ID.
*/
/**
* When page finished loading.
*
* @return When page finished loading.
*/ public final Date getEndLoad() { return endLoad;
}
/**
* When page finished loading.
*
* @param endLoad When page finished loading.
*/ public final void setEndLoad(final Date endLoad) { this.endLoad = endLoad;
}
/**
* When page starts loading.
*
* @return When page starts loading.
*/ public final Date getStartLoad() { return startLoad;
}
/**
* When page starts loading.
*
* @param startLoad When page starts loading.
*/ public final void setStartLoad(final Date startLoad) { this.startLoad = startLoad;
}
/**
* HttpResponse from the connection.
*
* @return HttpResponse from the connection.
*/ public final HttpResponse getHttpResponse() { return httpResponse;
}
/**
* HttpResponse from the connection.
*
* @param httpResponse HttpResponse from the connection.
*/ public final void setHttpResponse(final HttpResponse httpResponse) { this.httpResponse = httpResponse;
}
/**
* Initial time from the connection.
*
Chapter 1. Tealeaf installation and implementation in an Android application
37
public final Date getInitTime() { return initTime;
}
* @return Initial time from the connection.
*/
/**
* Initial time from the connection.
*
* @param initTime Initial time from the connection.
*/ public final void setInitTime(final Date initTime) { this.initTime = initTime; this.connectionInitFromSession = TLFCache.timestampFromSession();
}
/**
* Response time from the connection.
*
* @return Response time from the connection.
*/ public final long getResponseTime() { return responseTime;
}
/**
* Response time from the connection.
*
* @param responseTime Response time from the connection.
*/ public final void setResponseTime(final long responseTime) { this.responseTime = responseTime;
}
/**
* Get webview id.
*
* @return Webview id.
*/ public final PropertyName getWebViewId() { return webViewId;
}
/**
* Set webview id.
*
* @param webviewId Webview id.
*/ public final void setWebViewId(final PropertyName webviewId) { this.webViewId = webviewId;
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("PMD.NullAssignment")
@Override public void loadData(final String data, final String mimeType, final String encoding) { this.url = null; this.initTime = null; this.connectionInitFromSession = 0; this.responseTime = 0; this.httpResponse = null; this.startLoad = new Date(); super.loadDataWithBaseURL(this.url, data, mimeType, encoding, "");
}
38
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
/**
* {@inheritDoc}
*/
@SuppressLint("NewApi")
@Override public void loadUrl(final String url) { loadUrl(url, null);
}
/**
* {@inheritDoc}
*/ public final void loadUrl(final String url, final Map<String, String> extraHeaders) { this.url = url;
Tealeaf.setTLCookie(this.url); super.loadUrl(url, extraHeaders);
}
/**
* Initializes WebView.
*/ private void init() { setStartLoad(new Date());
// Need it when in Eclipse editor mode if (!this.isInEditMode()) { this.setWebViewClient(new UICWebViewClient()); this.setWebChromeClient(new UICWebChromeClient((Activity) this.getContext())); this.setWebViewId(Tealeaf.getPropertyName(this)); this.addJavascriptInterface(new JavaScriptInterface(this.getContext(), getWebViewId().getId()), "tlBridge");
}
}
/**
* Log the load time of the WebView.
*
* @return If log connection was added to queue.
*/ public final Boolean logConnection() { final long endTime = this.getEndLoad() != null ?
this.getEndLoad().getTime() : 0; final long startTime = this.getStartLoad() != null ?
this.getStartLoad().getTime() : 0; final long loadTime = endTime - startTime; return Tealeaf.logConnection(this.url, this.httpResponse, this.connectionInitFromSession, loadTime, this.responseTime);
}
}
Extend android.webkit.WebViewClient:
The sample code that follows extends the base Android WebViewClient with
UICWebViewClient .
/*******************************************************************************
* Licensed Materials - Property of IBM
* (C) Copyright IBM Corp. 2015
* US Government Users Restricted Rights - Use, duplication or disclosure
* restricted by GSA ADP Schedule Contract with IBM Corp.
******************************************************************************/ package com.tl.uic.webkit; import android.annotation.SuppressLint; import android.os.Build;
Chapter 1. Tealeaf installation and implementation in an Android application
39
import android.webkit.WebView; import android.webkit.WebViewClient;
/**
* @author ohernandezltmac
*
*/ public class UICWebViewClient extends WebViewClient {
/**
* {@inheritDoc}
*/
@Override public boolean shouldOverrideUrlLoading(final WebView view, final String url) { view.loadUrl(url); return true;
}
/**
* {@inheritDoc}
*/
@SuppressLint("NewApi")
@Override public void onPageFinished(final WebView view, final String url) {
// Get the call back mapping string to be evaluated/loaded as
Javascript code final String javascriptString = com.tl.uic.javascript.JavaScriptInterface.
hybridBridgeRegisterCallback(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { view.evaluateJavascript(javascriptString, null);
} else { view.loadUrl("javascript:" + javascriptString);
}
}
}
Sessionization for PhoneGap based Applications:
Since there are no requests and responses being sent back to the server, IBM
Tealeaf does not require extending of WebView to add sessionization.
Configuring DOM Capture and Replay for Native Android applications that cannot use PCA:
You configure DOM capture for a Native iOS application that cannot use PCA by modifying the defaultconfiguration.js file. If the HTML page in the webview does not fire on page load or if the page changes dramatically, you need to fire
DOM capture from within your Native Android application.
Before you do this task you must install the UIC library in your native application.
All of the modifications that you make are in your Native Android application.
1.
Modify the defaultconfiguration.js file and set the DOM Capture options that you want to use: replay: {
// DOM Capture configuration domCapture: { enabled: true,
// Filter object for matching rules is similar to the Privacy configuration
// It accepts a mandatory "event" followed by one or more optional targets
// as well as an optional delay after which to take the DOM snapshot.
40
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
triggers: [
{ event: "load"
}
],
// DOM Capture options removeScripts: true // Should script tags be removed from the captured snaphot
}
} options: { captureFrames: true, // Should child frames/iframes be captured
}
2.
If DOM Capture does not fire on load, set DOM Capture to fire from your application by adding this code to your Native Android application for the screenview that you want to capture: if (TLT === undefined) { console.log(’TLT is undefined!’);
} else { if (TLT.logScreenviewLoad === undefined) { console.log(’Could not invoke TLT.logScreenviewLoad API!’);
} else {
TLT.logScreenviewLoad("root"); console.log(’logScreenviewLoad:’);
} if (TLT.logDOMCapture === undefined) { console.log(’Could not invoke TLT.logDOMCapture API!’);
} else { dcid = TLT.logDOMCapture(window.document, {}); console.log(’logDOMCapture:’ + dcid);
}
}
Hybrid application bridge for Android APIs:
An Android hybrid application is a native application that uses WebView control as part of the UI components. Tealeaf Android SDK provides JavaScript interface
APIs integrated with CX UI Capture j2, which can be started from JavaScript functions to access native methods in hybrid application.
Tealeaf Android SDK APIs available to JavaScript
When you develop hybrid applications, you embed WebView component within a larger Android application. You can access exposed Android native methods from the UI Capture j2 global JavaScript object called "TLT" with methods that you use in your JavaScript code. This table lists and gives examples of the methods that you can include in your JavaScript code:
Method
Enable Tealeaf Framework
Example
/**
* Public API to enable Tealeaf framework.
* @returns {void}
*/ enableTealeafFramework();
Chapter 1. Tealeaf installation and implementation in an Android application
41
Method
Disable Tealeaf Framework
Log Screen Capture
Start New Tealeaf Session
Current Session ID
Default Value for Configurable Item
Value for Configurable Item
Example
/**
* Public API to disable Tealeaf framework.
* @returns {void}
*/ disableTealeafFramework();
/**
* Public API to add a screenshot capture.
* @returns {void}
*/ logScreenCapture();
/**
* Public API to start a new Tealeaf session.
* @returns {void}
*/ startNewTLFSession();
/**
* Public API to start get current
Tealeaf session Id.
* @returns {String} Current session
Id
*/ currentSessionId();
/**
* Public API to get default value of a configurable item in
* TLFConfigurableItems.properties
file.
* @param {String} configItem This is the name of the configurable item.
* @returns {String} The value for the item.
*/ defaultValueForConfigurableItem
(configItem);
/**
* Public API to get the value of a configurable item either from
* TLFConfigurableItems.properties
file
* or in memory data structure.
* @param {String} configItem This is the name of the configurable item.
* @returns {String} The value for the item.
*/ valueForConfigurableItem(configItem);
42
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
Method
Set Configurable Item
Add Additional HTTP Header
Log Custom Event Bridge
Example
/**
* Public API to set the value of a configurable item in
TLFConfigurableItems.properties
* file.
* @param {String} configItem This is the name of the configurable item.
* @param {String} value The value assign to the configItem.
* @returns {boolean} Wether item was set.
*/ setConfigurableItem(configItem, value);
/**
* Public API to add additional http header.
* @param {String} key This is the key of the configurable item.
* @param {String} value The value assign to the configItem.
* @returns {boolean} Wether item was set.
*/ addAdditionalHttpHeader(key, value);
/**
* Public API to log custom event.
* @param {String} eventName A custom event name.
* @param {String} jsonData JSON data string.
* @param {int} logLevel Tealeaf library logging level for the event.
* @returns {boolean} Wether item was set.
*/ logCustomEventBridge(eventName, jsonData, logLevel);
Example of how a native Android API is started
This example shows how to start a native method to enable Tealeaf Framework on a UI Capture j2 "TLT" instance using JavaScript:
<script type="text/javascript">
// Example of calling the native API to enable Tealeaf Framework using Javascript
TLT.enableTealeafFramework();
</script>
Sample test HTML file that starts supported native methods in JavaScript
This example is an HTML file that starts supported native methods in JavaScript:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<script type="text/javascript" src="js/tealeaf.js"></script>
<script type="text/javascript" src="js/defaultconfiguration.js" ></script>
<title>test APIs</title>
Chapter 1. Tealeaf installation and implementation in an Android application
43
<body>
<h2>Test page for Android bridge APIs in hybrid app</h2>
<h3>Click on below buttons to run tests:</h3>
<input type="button" style="width: 150px; height: 30px; font-size: 20px" value="Screen Capture" onclick="TLT.logScreenCapture();return false;"/>
<input type="button" style="width: 150px; height: 30px; font-size: 20px" value="Native APIs" onclick="runBridgeNativeTealeafAPIs();return false;"/>
<p/>
<p>Test native APIs output here:
<div id="queueData"></div>
</body>
<script type="text/javascript"> function htmlConsoleLog(textData, apiRetVal){ var para = document.createElement("p"); var node; if( apiRetVal !== undefined && apiRetVal !== null )
{
} else
{ node = document.createTextNode(textData + " returned: " + apiRetVal); node = document.createTextNode(textData );
} para.appendChild(node); var element = document.getElementById("queueData"); element.appendChild(para);
} function runBridgeNativeTealeafAPIs() { htmlConsoleLog( ’----- -------------------------------- -----’ ); htmlConsoleLog( ’----- Calling Tealeaf native APIs -----’ ); var apiRetVal = null; htmlConsoleLog( ’----- Calling enableTealeaf -----’ );
TLT.enableTealeafFramework(); apiRetVal = null; htmlConsoleLog( ’----- Calling currentSessionId -----’ ); apiRetVal = TLT.currentSessionId(); htmlConsoleLog( ’----- currentSessionId -----’, apiRetVal ); apiRetVal = null; htmlConsoleLog( ’----- Calling disableTealeaf -----’ );
TLT.disableTealeafFramework(); var apiRetVal = null; htmlConsoleLog( ’----- Calling enableTealeaf -----’ );
TLT.enableTealeafFramework(); apiRetVal = null; htmlConsoleLog( ’----- Calling currentSessionId -----’ ); apiRetVal = TLT.currentSessionId(); htmlConsoleLog( ’----- currentSessionId -----’, apiRetVal ); apiRetVal = null; htmlConsoleLog( ’----- Calling defaultValueForConfigurableItem
(PostMessageUrl) -----’ ); var PostMessageUrlVal = TLT.defaultValueForConfigurableItem
(’PostMessageUrl’); htmlConsoleLog( ’----- defaultValueForConfigurableItem -----’,
PostMessageUrlVal ); apiRetVal = null; htmlConsoleLog( ’----- Calling setConfigurableItem("PostMessageUrl",
"aValidPostUrl") -----’ );
44
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
apiRetVal = TLT.setConfigurableItem(’PostMessageUrl’, ’aValidPostUrl’); htmlConsoleLog( ’----- setConfigurableItem -----’, apiRetVal ); apiRetVal = null; htmlConsoleLog( ’----- Calling valueForConfigurableItem
("PostMessageUrl") -----’ ); apiRetVal = TLT.valueForConfigurableItem(’PostMessageUrl’); htmlConsoleLog( ’----- valueForConfigurableItem -----’, apiRetVal ); apiRetVal = null; htmlConsoleLog( ’----- Calling setConfigurableItem(PostMessageUrl,
’ + PostMessageUrlVal + ’) -----’ ); apiRetVal = TLT.setConfigurableItem(’PostMessageUrl’, PostMessageUrlVal ); htmlConsoleLog( ’----- setConfigurableItem -----’, apiRetVal ); apiRetVal = null; htmlConsoleLog( ’----- Calling valueForConfigurableItem
("PostMessageUrl") -----’ ); apiRetVal = TLT.valueForConfigurableItem(’PostMessageUrl’); htmlConsoleLog( ’----- valueForConfigurableItem -----’, apiRetVal ); apiRetVal = null; htmlConsoleLog( ’----- Calling startNewTLFSession -----’ ); apiRetVal = TLT.startNewTLFSession(); htmlConsoleLog( ’----- startNewTLFSession -----’, apiRetVal ); apiRetVal = null; htmlConsoleLog( ’----- Calling addAdditionalHttpHeader -----’ );
TLT.addAdditionalHttpHeader(’HeaderFromJavaScript’,
’HeaderValueFromJavaScript’); htmlConsoleLog( ’----- addAdditionalHttpHeader -----’ ); apiRetVal = null; htmlConsoleLog( ’----- Calling enableTealeaf again -----’ );
TLT.enableTealeafFramework(); apiRetVal = null; htmlConsoleLog( ’----- Calling currentSessionId -----’ ); apiRetVal = TLT.currentSessionId(); htmlConsoleLog( ’----- currentSessionId -----’, apiRetVal ); apiRetVal = null; var str = ’{\’key1AndroidBridge\’: \’value1AndroidBridge\’,
\’key2AndroidBridge\’: \’value2AndroidBridge\’}’; htmlConsoleLog( ’----- Calling logCustomEvent("Test Android Bridge Custom
Event",’ + str +’) -----’ ); apiRetVal = TLT.logCustomEventBridge(’Test Android Bridge Custom Event’, str, 0); htmlConsoleLog( ’----- logCustomEvent(Test Android Bridge Event, ’ + str +’ ) -----’, apiRetVal ); htmlConsoleLog( ’----- Done Calling Tealeaf native APIs -----’ ); htmlConsoleLog( ’----- -------------------------------- -----’ ); htmlConsoleLog( ’----- -------------------------------- -----’ ); htmlConsoleLog( ’----- -------------------------------- -----’ );
}
</script>
</head>
</html>
Accessing native Android methods with JavaScript with Tealeaf customized WebView:
When you crate hybrid applications, you can access native Android methods with
JavaScript, you use the Tealeaf customized WebView.
Chapter 1. Tealeaf installation and implementation in an Android application
45
Before you begin this task, you must:
1.
Install the most recent Tealeaf Android SDK.
2.
Implement the Android SDK following the instructions in the documentation.
3.
Include the most recent UI Capture j2 JavaScript source file.
1.
Add WebView to your application. Specify a length, height, weight, and ID that suits your application:
<WebView android:id="@+id/my_webview" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" />
2.
In your activity, locate the WebView and load your HTML file: public class MainActivity extends ActionBarActivity { private UICWebView mUICWebView; private String logicalPageName = "BridgeAppActivity";
@Override protected void onCreate(Bundle savedInstanceState) {
// Initialize tealeaf with a reference to application
Tealeaf tealeaf = new Tealeaf(this.getApplication()); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
// Load HTML file from local resource in the UICWebview mUICWebView = (UICWebView) findViewById(R.id.uic_webview);
// Modify the Url for your hybrid app mUICWebView.loadUrl("file:///android_asset/www/test.html");
WebSettings webSettings = mUICWebView.getSettings(); webSettings.setJavaScriptEnabled(true);
}
3.
Copy the application's HTML and JavaScript files to the /assets/www folder in your Android project.
Install the Eclipse Tealeaf plug-in for Android development in your application
Use of the Tealeaf Logging Frameworks for mobile native applications requires the
Tealeaf CX Mobile license for Mobile App. For more information, contact your
Tealeaf representative. Licensees must implement in their apps code that is provided by Tealeaf. For more information on downloading IBM Tealeaf, see IBM
Passport Advantage Online.
Install process
To install and configure the Eclipse Tealeaf plug-in in your Eclipse project you:
1.
Add the Eclipse Tealeaf plug-in to your project
2.
Convert your project to an Android + Tealeaf project
3.
Configure initial Eclipse Tealeaf plug-in properties
4.
Extend Android classes with or without the extended IBM Tealeaf classes.
Tealeaf package contents
A single file contains the Android SDK and its software components.
IBM Tealeaf Android SDK is delivered in the IBM Tealeaf Android SDK 8.8 - iOS
Logging Framework for Windows within the IBM Passport Advantage Online.
46
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
The package contains the following software components.
v KillSwitch . Code to implement the kill switch traffic manager for different server technologies.
– ASPX:
- killswitch.aspx: Page with logic.
- web.config: Configuration file that is used by the page.
– JSP:
- killswitch.jsp: Page with logic.
- config.properties: Configuration file that is used by the page.
– PHP
- killswitch.php: Page with logic.
- config.ini: Configuration file that is used by the page.
v PipelineAgents
- JSON parser for Android logging framework v UICAndroid :
– uicandroid.jar: Android library JAR file that contains the Android SDK.
– TLFConfigurableItems.properties: Configuration file.
v SampleCode : Contains the following versions of a sample Android application.
– UICSP_Clean: An Android application without IBM Tealeaf Android SDK integrated.
– UICSP_ManualLog: An Android application with IBM Tealeaf Android SDK integrated
– UICSP_ManualLog_ServerSessionID: An Android application with IBM Tealeaf
Android SDK integrated by using a session ID provided from a web application.
See "Sample Code" in the IBM Tealeaf Android SDK Guide.
v AndroidEclipsePlugin - An Eclipse Plug-in to assist with Tealeaf Integration.
– tealeaf.plugin.android.site-1.0.0-SNAPSHOT.zip The Plug-in archive to be added to your Eclipse IDE.
– tealeafandroidsdk.jar - Android Library JAR file that contains pre-instrumented Tealeaf widgets.
Android development environment requirements
To develop Android applications with the Android SDK, follow these system and software requirements.
Minimum requirements
Develop Android applications with a minimum API Level 8, which is Android 2.2
(Froyo).
Consult the Google Android Dev Center for the latest Android technical documentation and tools.
IBM Tealeaf client frameworks do not support forwarding of application data to third-party systems. Application data must be forwarded to the server that hosts the native application.
Chapter 1. Tealeaf installation and implementation in an Android application
47
Supported operating systems
Tealeaf supports these versions of the Windows, Mac, and Linux operating systems: v Windows XP (32-bit), Vista (32- or 64-bit), or Windows 7 (32- or 64-bit) v Mac OS X 10.5.8 or later (x86 only) v Linux (tested on Ubuntu Linux, Lucid Lynx)
– GNU C Library (glibc) 2.7 or later is required.
– On Ubuntu Linux, version 8.04 or later is required.
– 64-bit distributions must be able to run 32-bit applications. For information about how to add support for 32-bit applications, see the Ubuntu Linux installation notes.
Eclipse platforms
Tealeaf supports these Eclipse platforms: v Froyo 2.2
v Galileo 3.5
v Helios 3.6
v Indigo 3.7
v Juno 4.2
v Kepler 4.3
v
Tealeaf uses the Eclipse JDT plug-in (included in most Eclipse IDE packages).
For information on the Eclipse versions supported by the Android Development
Tools, check the Eclipse web sitehttp://www.eclipse.org/.
Eclipse packages
Several types of Eclipse packages are available for each platform. For developing
Android applications, install one of these packages.
v Eclipse IDE for Java Developers
– Java version 1.6.
– Java version 1.7 can be used in compatibility mode.
v Eclipse Classic v Eclipse IDE for Java EE Developers
– JDK 5 or JDK 6 (JRE alone is not sufficient).
– Android Development Tools plug-in
– Not compatible with GNU Compiler for Java (gcj)
Tealeaf impact on Android device resources
In benchmark tests, the Android SDK has the following effects on resources of the visitor's device.
v 2-3% more memory consumption v Minimal effect on battery life
48
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
Add Eclipse Tealeaf plug-in to your Eclipse Android project
After you acquire IBM Tealeaf Android SDK, install the Android SDK libraries into an Android application project.
Your Eclipse project must include the recommended frameworks. Testing of the
Android SDK involved Android 2.2 to 4.3.3.
Plug-in installed widgets
When you install the Eclipse Tealeaf plug-in, several widgets are installed. These widgets already have Tealeaf logging setup. This table lists and describes the widgets that are installed:
Widget
AutoCompleteTextView
Button
CheckBox
DatePicker
EditText
ExpandableListView
HorizontalScrollView
ImageButton
ImageView
LinearLayout
ListView
MultiAutoCompleteTextView
RadioButton
RadioGroup
RatingBar
Description
An editable text view that shows completion suggestions automatically while the user is typing.
Represents a push-button widget.
A two-states button that can be either checked or unchecked.
A widget for selecting a date by selecting a year, month, and day.
A thin veneer over TextView that configures itself to be editable.
A view that shows items in a vertically scrolling two-level list.
Layout container for a view hierarchy that can be scrolled by the user, allowing it to be larger than the physical display.
Displays a button with an image (instead of text) that can be pressed or clicked by the user.
Displays an arbitrary image, such as an icon.
A Layout that arranges its children in a single column or a single row.
A view that shows items in a vertically scrolling list.
An editable text view, extending
AutoCompleteTextView , that can show completion suggestions for the substring of the text where the user is typing instead of necessarily for the entire thing.
A radio button is a two-states button that can be either checked or unchecked.
This class is used to create a multiple-exclusion scope for a set of radio buttons. Checking one radio button that belongs to a radio group clears any previously checked radio button within the same group.
An extension of SeekBar and ProgressBar that shows a rating in stars.
Chapter 1. Tealeaf installation and implementation in an Android application
49
Widget
RelativeLayout
ScrollView
SeekBar
Spinner
Switch
TextView
TimePicker
ToggleButton
Description
A Layout where the positions of the children can be described in relation to each other or to the parent.
Layout container for a view hierarchy that can be scrolled by the user, allowing it to be larger than the physical display.
An extension of ProgressBar that adds a draggable thumb.
A view that displays one child at a time and lets the user pick among them.
A two-state toggle switch widget that can select between two options.
Displays text to the user and optionally allows them to edit it.
A view for selecting the time of day, in either 24 hour or AM/PM mode.
Displays checked/unchecked states as a button with a "light" indicator and by default is accompanied with the text "ON" or "OFF".
Adding the Eclipse Tealeaf plug-in to your project
You install the Eclipse Tealeaf plug-in JAR file in your Eclipse project to use Tealeaf with your project.
Before you begin, you must install: v Eclipse v Java v Android Development Toolkit
You must also have the location of the Eclipse Tealeaf plug-in installation files.
At the end of this task you are asked to restart Eclipse. Do this task when restarting Eclipse will not impact your work.
1.
Extract the TLFLibRelease.zip file. The Tealeaf folder is extracted. The Tealeaf folder contains all necessary files for the Android SDK and the plug-in.
2.
Open your project in Eclipse.
3.
From the Help menu, select Install New Software...
4.
In the Install window, select Add....
5.
In the Add window define the repository for the Eclipse Tealeaf plug-in files: a.
Enter a name for the Tealeaf and plug-in repository that you are creating.
b.
Enter the location of the files. If the files are on your local machine, select
Local...
and navigate to the files. If the files are in a compressed file or JAR file on your local machine, select Archive... and navigate to the files. If the files are on a website, enter the URL for the website in the Location: field.
c.
Click OK.
6.
In the Install window, select the files to install and click Next.
7.
Accept the license agreement.
8.
Click Finish to complete the installation.
50
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
9.
When prompted, restart Eclipse.
Converting your project to Android+Tealeaf
After you install the Tealeaf software in Eclipse and restart Eclipse, you convert your project to an Android + Tealeaf project. The convert process installs JAR and properties files in your project and installs a custom widgets library that you can use with your project. The first time you convert a project, you are prompted for the JAR file that installs the Tealeaf Android library file.
1.
Open your project in Eclipse.
2.
Right-click on your project and select Configure > Convert to Android +
Tealeaf project
.
3.
If this is the first time that you are using the plug-in you are asked for the
Tealeaf SDK: a.
Navigate to the repository where the Tealeaf software is located.
b.
Select the tealeafandroidsdk.jar file.
c.
Click Open.
4.
In your project, open the Custom & Library Views.
5.
Click Refresh to see the custom widgets that were added.
Configure Tealeaf properties
You configure several items for your app in Tealeaf, including how screen layouts are logged, Target page location, kill switch location, and whether gestures will be logged.
TLFConfigurableItems.properties
Everything that you configure is in the TLFConfigurableItems.properties file. The
TLFConfigurableItems.properties
file is in the Install Package.
Configurable properties
There are many properties that you can configure in Tealeaf. At the minimum, you must configure: v Whether to display logcat messages.
v The Target page URL.
v Enable/disable the kill switch URL v The kill switch URL.
v How screen layouts are logged.
v
The logging level.
For information to the other properties that you can configure, go to <link to reference topic that I don't have access to right now>.
Whether to display logcat messages
Whether you see logcat messages is set with the DisplayLogging property.
Set Target URL
All events that are captured are sent in JSON format to a Target page. The Target page acknowledges the receipt of the JSON message and forwards the client-side events to Tealeaf. The person that sets up Tealeaf on the server creates the Target
Chapter 1. Tealeaf installation and implementation in an Android application
51
page. The Target page is set with the PostMessageUrl property.
Enable and set kill switch
The Kill Switch is used to control logging. When the kill switch is enabled, it must have a URL to check before the framework initializes. When the page is reachable, the framework initializes. If the page is not reachable, because of network problems or because you disabled it on your server, the framework does not initialize. The kill switch URL is set by the person who sets up Tealeaf on the server. The kill switch is enabled with the KillSwitchEnabled property. The kill switch URL is set with theKillSwitchUrl property.
How screen layouts are logged
Tealeaf can log screen images as base64 or as MD5 checksum with png or jpg images. Set GetImageDataOnScreenLayout to YES to capture base 64 data. Set
GetImageDataOnScreenLayout to NO to log MD5 checksum and png or jpg images.
This option creates smaller payloads in production and is the recommended setting.
Set logging level
You set the logging level based on where your project is in the development cycle.
You can set the level high for development and testing and then lower the logging level for production. The logging level is set with the LoggingLevel property.
Auto-instrumentation
Android enables the use of one handler at a time for any object. As a result, auto-instrumentation is not supported in Tealeaf. You must apply instrumentation as part of your application development.
Configuring Tealeaf properties for your application
You configure Tealeaf to use specific URLS for logging events and to control message flow, set how screen layouts are logged, modify logging levels.
All of the configuration in this task involves modifying settings in the
TLFConfigurableItems.properties
file in the Assets folder of your Eclipse project.
1.
In your Eclipse, open the TLFConfigurableItems.plist file.
2.
Set the DisplayLogging to False.
3.
Set the PostMessageUrl to the URL of the target page for your app.
4.
Set the KillSwitchEnabled to True.
5.
Set the KillSwitchUrl to the URL for the kill switch for your app.
6.
Set the GetImageDataOnScreenLayout to False.
7.
Set the LoggingLevel to an appropriate level for development, testing, or production.
8.
Save and exit the TLFConfigurableItems.properties file.
Extended Android classes
You extend Android classes to provide logging for components in your application.
You can extend the classes with the IBM Tealeaf extended classes or you can extend the classes manually. If you install the Tealeaf SDK, you must extend the
Application and Activity classes. When you install the Eclipse Tealeaf plug-in, you
52
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
must extend only the Activity class. How you extend the classes depends on whether you have custom Application or Activity classes.
Application class
You extend the Activity class to automatically capture points the lifecycle of a native Android application page. Tealeaf listens to these events: v onLowMemory - disable the library when you get a LowMemory warning v onCreate - initialize the library when the application starts v onTerminate - clean up the library when the application is terminated
How you extend the Application class depends on whether you have a custom activity class for your application. If you: v Do not have a custom Application class for your application, use the IBM
Tealeaf class UIApplication. You do this only if you are not using the Eclipse
Tealeaf plug-in. The plug-in automatically extends the Application class with the
Tealeaf UICApplication class.
v Have a custom Activity class for your application, modify your custom
Application class to point to the Tealeaf UICApplication class.
Application class and the Eclipse Tealeaf plug-in
After you install the Eclipse Tealeaf plug-in, if you decide to use a custom
Application class in your application, you need to change the Application class automatically added by the plug-in:
1.
Create the custom Application class.
2.
Modify AndroidManifest.xml file for the application and change the application class name to the name of Application class you created.
Activity class
You extend the Activity class to automatically capture points the lifecycle of a native Android application page. Tealeaf listens to these events: v onPause - what happens when the application goes to the background v onResume - what happens when the application goes to the foreground v onDestroy - what happens when the activity is no longer in memory and gets garbage collected
How you extend the Activity class depends on whether you have a custom activity class for your application. If you: v Do not have a custom Activity class for your application, use the Tealeaf
UIActivity class.
v Have a custom Activity class for your application, modify your custom Activity class to point to the Tealeaf UICActivity class.
Extending the Application class with the Tealeaf UICApplication class
If you do not have a custom Application class, you can use the IBM Tealeaf
UICApplication class to extend the Application class. The application file manages the lifecycle of an Android application. IBM Tealeaf manages the library by listening to onLowMemory to disable library if you get a warning, onTerminate to clean up library, and onCreate to initialize the library.
Chapter 1. Tealeaf installation and implementation in an Android application
53
1.
Open the existing Java file that extends from application class. If this file does not exist, you must create it and have it listen to the complete lifecycle of an
Android application to control library and log information needed. You must also change the file to extend from com.tl.uic.app.UICApplication instead of android.app.Application
.
2.
Add these imports: a.
import com.tl.uic.Tealeaf; b.
import com.tl.uic.app.UICApplication;
3.
In onCreate() method, add Tealeaf.enable() that initializes capture of user actions in the application.
4.
Adjust AndroidManifest.xml to indicate application class. For example, if your application class is named MyApplication, you can add
⌂android:name=".MyApplication" in <application> node.
5.
Add the following permissions in AndroidManifest.xml.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.SET_DEBUG_APP" />
This example shows the lines that you add to the AdroidManifest.xml file: import com.tl.uic.Tealeaf; import com.tl.uic.app.UICApplication; public class MyApplication extends UICApplication {
@Override public void onCreate() { super.onCreate();
Tealeaf.enable();
}
}
Extending the Activity class with the Tealeaf UICActivity class
The activity file manages the lifecycle of a page in a native Android application similar to what a page does in a web application. IBM Tealeaf listens to the following events onPause, which happen when application goes to the background, onResume , which happens when application goes to foreground, and onDestroy when activity is no longer in memory and gets garbage collected.
On each activity files that you want to log, extend it using UICActivity. Using
UICActivity extends the base Activity from the Android framework. UICActivity adds some functionality that is required by the IBM Tealeaf Logging Framework library to enable and disable asynchronous tasks, and to perform screen captures of the device after creation.
To avoid capturing potentially private data, the Android SDK takes screen captures as soon as the image was rendered on the device. As a result, no user-defined fields are populated in any captured screen image.
Android does not support capture of pop-up windows.
For hybrid applications, screen captures might be missing or out of order due to timing issues.
54
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
The method in this task enables automatic capture of screen captures from the client application. If you do not enable this item through UICActivity, you can manually capture screen captures through the Logging Framework. See "Reference" in the IBM Tealeaf Android SDK Guide.
The value for the black background color can be replaced by any color constant to set the color of the background of your screen captures.
1.
Open the existing Java file that extends from android.app.Activity class, and change it to extend from com.tl.uic.app.UICActivity instead of android.app.Activity
.
2.
Add these imports: a.
Import com.tl.uic.Tealeaf; b.
Import com.tl.uic.app.UICApplication;
3.
In the onCreate() method, add: a.
Add this.setTakeSnapshotAfterCreate(true); //To enable automatic screen shots .
b.
Add setLogicalPageName("LoginPage") //Recommended to identify page.
c.
Add setImageBackground(-16777216) //To set to black background of screenshot because the screen capture background is transparent.
This example shows the lines that you add to the file that extends the Activity class: import com.tl.uic.app.UICActivity; public class LoginActivity extends UICActivity {
@Override public void onCreate(Bundle savedInstanceState) { this.setTakeSnapshotAfterCreate(true); //To enable automatic screen shots setLogicalPageName("LoginPage") //Recommended to identify page setImageBackground(-16777216) screenshot
//To set to back background of super.onCreate(savedInstanceState);
Extending your custom Application class to point to the Tealeaf
UICApplication class
If you have a custom Application class in your application, point your custom class to the Tealeaf UICApplication class. The application file manages the lifecycle of an
Android application. IBM Tealeaf manages the library by listening to onLowMemory to disable library if you get a warning, onTerminate to clean up library, and onCreate to initialize the library. .
1.
Open the existing Java file that extends from the android.app.Application
class. If this file does not exist, you must create it and have it listen to the complete lifecycle of an Android application to control library and log information needed.
2.
Add this import: import com.tl.uic.Tealeaf;
3.
In onCreate(): a.
Add Tealeaf tealeaf = new Tealeaf(this);, which initializes the IBM
Tealeaf library with a reference to application instrumented.
b.
Add Tealeaf.enable(); that initializes capture of user actions in the application.
4.
In onLowMemory(): a.
Add Tealeaf.onLowMemory(); before super so it can adjust the library due to low memory.
Chapter 1. Tealeaf installation and implementation in an Android application
55
5.
In onTerminate(): a.
Add Tealeaf.disable(); before super so it can disable the library.
6.
Adjust AndroidManifest.xml to indicate application class. For example, if your application class is named MyApplication, you can add
⌂android:name=".MyApplication" in <application> node.
7.
Add these permissions to AndroidManifest.xml.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.SET_DEBUG_APP" />
This example shows the lines you add to the file that extends the Application class: import android.app.Application; import com.tl.uic.Tealeaf; public class MyApplication extends Application {
@Override public void onCreate() { super.onCreate();
Tealeaf tealeaf = new Tealeaf(this);
Tealeaf.enable();
}
@Override public void onLowMemory() {
Tealeaf.onLowMemory(); super.onLowMemory();
}
}
@Override public void onTerminate() {
Tealeaf.disable(); super.onTerminate();
}
Extending your custom Activity class to point to the Tealeaf
UICActivity class
If you have a custom Activity class, extend it to point to the Tealeaf UICActivity class. The activity file manages the lifecycle of a page in a native Android application similar to what a page does in a web application. IBM Tealeaf listens to the following events onPause, which happen when application goes to the background, onResume, which happens when application goes to foreground, and onDestroy when activity is no longer in memory and gets garbage collected.
Each activity needs a logical page name that helps indicate what activity is being displayed. If no logical page name is given, IBM Tealeaf recommends using class name that gives some indication what activity is being displayed.
1.
Open the existing Java file that extends from android.app.Activity class, and change it to extend from com.tl.uic.app.UICActivity instead of android.app.Activity
.
2.
Add this import: a.
Import com.tl.uic.Tealeaf;
3.
Add the logical page name to the class: private String logicalPageName; public final String getLogicalPageName() { if ((this.logicalPageName == null) ||
(this.logicalPageName.equals(""))) {
56
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
this.logicalPageName = this.getClass().getName().substring(this.getClass()
.getName().lastIndexOf(".") + 1);
} return this.logicalPageName;
}
4.
In the onPause() method, add: a.
Add Tealeaf.onPause(this, getLogicalPageName());
5.
In the onResume() method, add: a.
Add Tealeaf.onResume(this, getLogicalPageName());
6.
In the onDestroy() method, add: a.
Add Tealeaf.onDestroy(this, getLogicalPageName());
This example shows the lines that you add to the file that extends your custom
Activity class: import com.tl.uic.Tealeaf; public class BaseActivity extends Activity { private String logicalPageName;
/**
* Logical page name of the Activity.
*
* @return Logical page name of the Activity.
*/ public final String getLogicalPageName() { if ((this.logicalPageName == null) ||
(this.logicalPageName.equals(""))) { this.logicalPageName = this.getClass().getName().substring(this.getClass().
getName().lastIndexOf(".") + 1);
} return this.logicalPageName;
}
/**
* Logical page name of the Activity.
*
* @param logicalPageName
* Logical page name of the Activity.
*/ public final void setLogicalPageName(final String logicalPageName) { this.logicalPageName = logicalPageName;
} protected void onPause() {
Tealeaf.onPause(this, getLogicalPageName()); super.onPause();
} protected void onResume() {
Tealeaf.onResume(this, getLogicalPageName()); super.onResume();
}
} protected void onDestroy() {
Tealeaf.onDestroy(this, getLogicalPageName()); super.onDestroy();
}
Chapter 1. Tealeaf installation and implementation in an Android application
57
Implement Tealeaf
After you install Tealeaf, you complete several tasks to implement Tealeaf functions in your application. These tasks involve modifying your application to capture controls, events, and screen views.
Implementation tasks
After you install the SDK, you must complete more tasks to implement the SDK.
All of these tasks must be done for both the Tealeaf SDK and Eclipse Tealeaf plug-in for Tealeaf to work. All of these tasks are manual.
This table lists and describes the tasks that you complete to implement Tealeaf in your application:
Task
Log Screen Layout for Android Mobile App
Replay
Tealeaf SDK ONLY
Integration for Apache Cordova, PhoneGap, and IBM Worklight applications that use
Android classes without IBM Tealeaf classes
Implementing screenViews
Target page configuration
Data privacy
Configuring sessionization for Android applications on the client
Network traffic that is used in application contains requests only
Configure requests in Android application
Description
Configure logging screen layout to use JSON data not screen captures. Includes configuring logical pages names, alert dialogs, and keyboard events.
Integrate Cordova, PhoneGap, and IBM
Worklight applications in your application.
Includes extending the Application class for onCreate, onLowMemory, onTerminate methods and onPause, on'Resume, and onDestroy methods for Cordova.
Implementing screenViews as segments for pages in which the state or context can be switched without rerendering the page.
Set up the target page that acknowledges that events are captured.
Specify the fields that are blocked or masked during capture.
Configure how session IDs are generated.
Uses non-IBM Tealeaf session ID
Hybrid application
Tealeaf supports network traffic that is used in applications that contain requests only.
Configure Tealeaf to put session identifiers in cookies.
Configure your generated session IDs to be used when sessions are enabled or new sessions started.
Configure your application to log request activity if you have a WebView in your application.
Log screen layout for mobile app session replay
IBM Tealeaf has functions to log screen layouts for screenviews of native mobile app sessions. You can replay a mobile app session in cxImpact Browser Based
Replay as you would an HTML web session instead of viewing the mobile app session as a series of screen captures.
The screen layouts of the native mobile app sessions are captured in IBM Tealeaf
JSON format. The screen layouts are then sent back to replay server. The replay
58
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
server uses a template engine, which interprets the JSON into HTML format. You can then replay the screen layout from the native mobile app session as HTML pages in cxImpact Browser Based Replay.
There are several advantages to using JSON data to replay mobile app session over screen captures.
v Reduce bandwidth. Screen captures for each screenview generate relatively large image data. It not only consumes large amounts of wireless and cellular bandwidth, but it also consumes more memory inside the device. It also impacts the app performance.
v Mask sensitive information. You cannot mask sensitive information in a screen capture. When you use JSON data to replay mobile app sessions, you can mask
EditTexts by adding View IDs to the MaskIdList attribute in
TLFConfigurableItems.properties
.
v
Draw user interactions (UI events) onto the HTML pages that are created from the JSON data.
For more information on mobile ap session replay templates, see "Native app session replay customization" in the IBM Tealeaf CX Configuration Manual.
TLFConfigurableItems.properties
changes
For native app session replay to be activated, you must set
LogViewLayoutOnScreenTransition to true. If you do not, the library functions as it currently does.
#Capture native layout
LogViewLayoutOnScreenTransition=true
During predeployment, you must perform all the replay cases to collect all the images with GetImageDataOnScreenLayout set to true. This creates a large payload sent to server that contains base64 images that are used for replay. When the application is ready to be deployed to Play Store, GetImageDataOnScreenLayout must be changed to false.
#Current only done on ImageView
GetImageDataOnScreenLayout=true
Understand your activity
In Android, an Activity can be considered a page, which is displayed on mobile device. By default, you should record an activity that is displayed.
For more information, see http://developer.android.com/training/basics/activitylifecycle/starting.html.
You can record an activity that is displayed, by placing the following information in the OnCreate method.
// this will indicate logical page name.
Tealeaf.logScreenview(activity, "Name", ScreenviewType.LOAD);
// this will get layout of page after it being created.
Tealeaf.logScreenLayoutOnCreate(activity, "Name");
If you need to log a layout, you can use the following.
Tealeaf.logScreenLayout(activity, "Name", delayInMS);
Chapter 1. Tealeaf installation and implementation in an Android application
59
Replaying AlertDialogs
You need to know when an alert dialog is displayed so it can be captured correctly.
OnShowListener is correct location to use for this.
// This will capture background and alert when it is displayed.
Tealeaf.logScreenLayoutSetOnShowListener(activity, dialog);
If there is already a OnShowListener, follow this example.
// This is placed inside OnShowListener:
Tealeaf.logScreenLayout(activity, dialog);
To capture an alert dialog event, follow this example.
public void onClick(DialogInterface dialog, int id) {
Tealeaf.logDialogEvent(dialog, id);
Replaying keyboard events
Android does not provide an event to understand when a soft keyboard appears and disappears. Follow this example to make the necessary adjustments to
TextView based controls.
public static void addFocusAndRegister(TextView textView, Activity activity) { textView.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) {
InputMethodManager imm = (InputMethodManager) v.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(v, InputMethodManager.SHOW_FORCED);
KeyboardView keyboardView = new KeyboardView(v.getContext()
.getApplicationContext(), null);
Tealeaf.logEvent(keyboardView , Tealeaf.TLF_UI_KEYBOARD_
DID_SHOW_NOTIFICATION);
Tealeaf.logEvent(v, Tealeaf.TLF_ON_FOCUS_CHANGE_IN);
} else {
Tealeaf.logEvent(v, com.tl.uic.Tealeaf.TLF_ON_FOCUS_CHANGE_OUT);
InputMethodManager imm = (InputMethodManager) v.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
KeyboardView keyboardView = new KeyboardView(v.getContext()
.getApplicationContext(), null);
Tealeaf.logEvent(keyboardView , Tealeaf.TLF_UI_KEYBOARD
_DID_HIDE_NOTIFICATION);
}
}
});
Tealeaf.registerFormField(textView, activity);
}
EditText et = (EditText) findViewById(R.id.editText1); addFocusAndRegister(et, this);
For more information, review ControlsActivity3.java in the Sample Code project,
UICAndroidControlsAppdarkHolo .
Supported controls
IBM Tealeaf replays controls that are extended from the following controls. For each control, IBM Tealeaf fills in the tlType value in the json object that is sent back to the server.
60
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
ToggleButton and Switch
Uses switch template
RadioGroup and RadioButton
Uses radioButton template
CheckBox
Uses checkBox template
Button
Uses button template
Scroller, HorizontalScrollView, ScrollView
Uses scroll template
AbsSeekBar
Uses slider template
ProgressBar
Uses progressSpinner or progressBar template
AbsSpinner
Uses selectList template
EditText
Uses label template
TextView
Uses switch template
ImageView
Uses image template
FrameLayout, LinearLayout, ViewStub, View
Uses canvas template
AbsListView
Uses grid template
AlertDialog
Uses alert template
TabWidget
Uses tabBar template
TabHost
Uses tabContainer template
Integration for Apache Cordova, PhoneGap, and IBM Worklight applications using Android classes without IBM Tealeaf classes
This method has developers add code snippets that help the IBM Tealeaf capture library.
android.app.Application file code changes:
The application file manages the lifecycle of an Android application. IBM Tealeaf manages the library by listening to onLowMemory to disable library if you get a warning, onTerminate to clean up library, and onCreate to initialize the library. IBM
Tealeaf recommends this as a best practice.
Chapter 1. Tealeaf installation and implementation in an Android application
61
Locating the file that extends from android.app.Application
This file most likely will not exist so you must create it and add it to listen to the complete lifecycle of an Android application to control library and log information needed.
1.
Create application class from android.app.Application and add the following.
If application class is found, then continue to the next steps.
2.
Open the existing Java file that extends from android.app.Application class.
3.
Add the following imports.
a.
import com.tl.uic.Tealeaf; b.
import com.tl.uic.app.UICApplication;
4.
In onCreate(): a.
Add Tealeaf tealeaf = new Tealeaf(this);, which initializes the Tealeaf library with a reference to application instrumented.
b.
Add Tealeaf.enable(); that initializes capture of user actions in the application.
5.
In onLowMemory(): a.
Add Tealeaf.onLowMemory(); before super so it can adjust library due to low memory.
6.
In onTerminate():: a.
Add Tealeaf.disable(); before super so it can disable library.
7.
Adjust AndroidManifest.xml to indicate application class, by adding android:name=".MyApplication" .
Example in Application class
import android.app.Application; import com.tl.uic.Tealeaf; public class MyApplication extends Application {
@Override public void onCreate() { super.onCreate();
Tealeaf tealeaf = new Tealeaf(this);
Tealeaf.enable();
}
@Override public void onLowMemory() {
Tealeaf.onLowMemory(); super.onLowMemory();
}
}
@Override public void onTerminate() {
Tealeaf.disable(); super.onTerminate();
}
Example in AndroidManifest.xml
<application android:label="@string/app_name" android:debuggable="true" android:icon="@drawable/icon" android:name=".TLWorklightTealeafApplication" >
62
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
org.apache.cordova.DroidGap, com.worklight.androidgap.WLDroidGap file code changes:
The file extends from Activity class, which manages the lifecycle of a page in a native Android application similar to what a page does in a web application.
IBM Tealeaf listens to the following events onPause, which happen when application goes to the background, onResume, which happens when application goes to foreground, and onDestroy when activity is no longer in memory and gets garbage collected.
Locating the file that extends from org.apache.cordova.DroidGap, com.worklight.androidgap.WLDroidGap
1.
Open the existing Java file that extends from android.app.Activity.
2.
Add the following imports.
a.
import com.tl.uic.Tealeaf; b.
import com.tl.uic.app.UICApplication; c.
import com.tl.uic.model.ScreenviewType;
3.
Each activity needs a logical page name that helps indicate what activity is currently being displayed. If no logical page name is given, IBM Tealeaf recommends to use class name that gives some indication what activity is being display.
Add the following to class: private String logicalPageName = "MainPage";
4.
In onPause() method: a.
Add Tealeaf.onPause(this, logicalPageName);
5.
In onResume() method: a.
Add Tealeaf.onResume(this, logicalPageName);
6.
In onDestroy() method: a.
Add Tealeaf.onDestroy(this, logicalPageName);
7.
In onCreate(), add after super.onCreate( a.
Tealeaf.logScreenview(this, logicalPageName, ScreenviewType.LOAD); b.
appView.addJavascriptInterface(new
JavaScriptInterface(this.getContext(),
Tealeaf.getPropertyName(webviewObject).getId()), "tlBridge");
Example from IBM Worklight
package com.TLWorklightTealeaf; import android.os.Bundle; import com.tl.uic.Tealeaf; import com.tl.uic.javascript.JavaScriptInterface; import com.tl.uic.model.ScreenviewType; import com.worklight.androidgap.WLDroidGap; public class TLWorklightTealeaf extends WLDroidGap { private String logicalPageName = "MainPage";
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
// Log Screenview for this activity
Chapter 1. Tealeaf installation and implementation in an Android application
63
Tealeaf.logScreenview(this, logicalPageName, ScreenviewType.LOAD);
//DeviceAuthManager.getInstance().setProvisioningDelegate(<Use default
ProvisioningDelegateImpl class or replace with your
IProvisioningDelegate implementation>);
// Add bridge for Tealeaf data to be sent back appView.addJavascriptInterface(new JavaScriptInterface(this.getContext(),
Tealeaf.getPropertyName(webviewObject).getId()), "tlBridge");
} super.loadUrl(getWebMainFilePath());
} public void onPause() {
// Handle Tealeaf during onPause event
Tealeaf.onPause(this, logicalPageName); super.onPause(); public void onResume() {
// Handle Tealeaf during onResume event
Tealeaf.onResume(this, logicalPageName); super.onResume();
} public void onDestroy() {
// Handle Tealeaf during onResume event
Tealeaf.onDestroy(this, logicalPageName); super.onDestroy();
}
}
Implementing screenViews
For pages in which the state or context can be switched without re-rendering the page, IBM Tealeaf segments the data between states by using a screenView object.
For example, if a page contains multiple tabs, each of which represents a different stage in a checkout process, you instrument each tab in the page as a distinct screenView.
To implement a screenView for a page, complete the following steps.
1.
If you are extending from UICActivity, set a logicalPageName to indicate the use of the activity. Otherwise, logicalPageName is set to the name of the class of the activity.
2.
If the prior step is not complete, call Tealeaf.logScreenview and pass the logicalPageName . You must also indicate if the page being loaded and unloaded is optional. For example:
Tealeaf.logScreenview(activity, logicalPageName, ScreenviewType.LOAD);
Tealeaf.logScreenview(activity, logicalPageName, ScreenviewType.UNLOAD);
Basic configuration
You must set up a target page on your web server.
See “Quick start for server configuration” on page 88.
Set the target page's address in the TLFConfigurableItems.properties
configuration file under the key PostMessageUrl.
See "Configuration File" in the IBM Tealeaf Android SDK Guide.
64
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
Data privacy
IBM Tealeaf provides mechanisms for masking or blocking sensitive customer information, such as credit card numbers, from being transmitted and captured by
IBM Tealeaf. Through the Android SDK, you can specify the fields that need to be blocked or masked in your web application.
When applied, data privacy ensures that these data elements are never transmitted to IBM Tealeaf.
Note:
Due to changes in how client framework data is submitted to IBM Tealeaf for capture, the best method for masking or blocking sensitive data is to apply the filtering through the capturing client framework. While other IBM Tealeaf features to manage data privacy can be deployed, they are not easy to implement on the new format of data captured from the client frameworks. IBM Tealeaf recommends using the methods referenced below.
v
See "Configuration File" in the IBM Tealeaf Android SDK Guide.
v For more information about handling sensitive data in general, see "Managing
Data Privacy in Tealeaf CX" in the IBM Tealeaf CX Installation Manual.
Configuring sessionization for Android applications on the client
The Android SDK auto-generates a session ID if one is not provided. This session
ID is used to identify the session on the IBM Tealeaf server.
IBM Tealeaf injects cookies to create session in the IBM Tealeaf system.
Note:
When an Android native or hybrid application is placed into background, the library flushes the collected data and sleeps, instead of disabling it. This happens unless the session expired due to the session timeout property. The timeout property is indicated with SessionTimeout in
TLFConfigurableItems.properties
. The default value for this property is 30 minutes. After a 30-minute timeout, a new session identifier is created.
There are two ways to configure sessionization; either through TLTSID provide by
IBM Tealeaf, or through customer session ID, called JSESSIONID. Both methods function as a unique session identifier within the Android SDK environment for
IBM Tealeaf to track on customer sessions. CookieParam can be set to use customer session ID or JSESSIONID.
The following is a typical setting in TLFConfigurableItems.properties using customer session ID.
#Sessionization settings on customer cookies
CookieUrl = http://www.sample.com
CookieDomain = .sample.com
CookiePath = /
CookieParam = JSESSIONID
CookieExpires = false
SessionTimeout=30
SessoinTimeoutKillSwitch=false
In this example, the cookie expires 30 minutes from current time. When the session timeout occurs, Android SDK retrieves the new cookie from your application server and posts the rest of request to application server using this new acquired cookie in request header. PCA groups all the used JSESSIONIDs into one single session even though the JSESSIONID was consistently changing. When using cookies generated from customer application server, SessoinTimeoutKillSwitch can
Chapter 1. Tealeaf installation and implementation in an Android application
65
be set to true or false. Setting the SessoinTimeoutKillSwitch to false means the session timeout user does not go to recheck on KillSwitchUrl to see if it is responding.
Network traffic used in application contains requests only:
Android SDK uses cookies to add values to the TLFConfigurableItems.properties
file.
Uses session ID generated by IBM Tealeaf Android SDK
Android SDK uses cookies to add the following values in
TLFConfigurableItems.properties
.
v CookieUrl is for url of site that is posted and getting cookie to sessionize on.
v CookieParam is the parameter that has a session id.
v CookiePath is the path of the cookie.
v CookieDomain is the domain that the cookie belongs to.
v CookieSecure is to add a secure cookie that can only be posted to an https url that has a valid certificate.
v CookieExpiresFormat can have the date format of ASCTIME, RFC1036, or
RFC1123, which will have an expiration date of current time + session timeout indicated in the variable below.
v SessionTimeout is session timeout is in minutes. When this value expires a new session id is created.
An example follows.
#Sessionization settings
CookieUrl=http://m.ibm.com
CookieParam=TLTSID
CookiePath=/
CookieDomain=.ibm.com
#Whether you want to create a secure cookie which can only be sent using a https url in PostMessageUrl.
CookieSecure=false
#Valid date formats: ASCTIME, RFC1036, RFC1123
CookieExpiresFormat=ASCTIME
#When post is sent, expiration of cookie will be current time + session timeout
#Session timeout is in minutes
SessionTimeout=30
Note:
It is important to first call your server to get first cookie to sessionize on, which is automatically obtained when you enable the kill switch URL on the application. This is used to aggregate all the data on CX Passive Capture
Application capture.
Configure requests in Android application
IBM Tealeaf needs all the requests to have the session id to be placed in the cookies of the request. This enables the IBM Tealeaf system to collect all the resources together in a single session.
If you are using org.apache.http.impl.client.DefaultHttpClient, you can use com.tl.uic.http.TLDefaultHttpClient
, which adds the appropriate session id in the cookie of the request. If you decide not use the IBM Tealeaf extended class, then you must add the following code to the following classes.
66
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
Extend org.apache.http.impl.client.DefaultHTTPClient:
If you do not use the IBM Tealeaf extended TLDefaultHttpClient class, you must add the following code to the following classes.
import org.apache.http.conn.ClientConnectionManager; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpParams;
/**
* @author ohernandez
*
*/ public class TLDefaultHttpClient extends DefaultHttpClient {
/**
*
*/ public TLDefaultHttpClient() { super(); this.init(null);
}
/**
* @param params Http parameters.
*/ public TLDefaultHttpClient(final HttpParams params) { super(params); this.init(null);
}
/**
* @param params Http parameters.
* @param sessionId Tealeaf session id.
*/ public TLDefaultHttpClient(final HttpParams params, final String sessionId) { super(params); this.init(sessionId);
}
/**
* @param conman ClientConnectionManager.
* @param params Http parameters.
*/ public TLDefaultHttpClient(final ClientConnectionManager conman, final HttpParams params) { super(conman, params); this.init(null);
}
/**
* @param sessionId Tealeaf session id.
*/ private void init(final String sessionId) { final TLHttpRequestInterceptor tlHttpRequestInterceptor = new TLHttpRequestInterceptor(sessionId); this.addRequestInterceptor(tlHttpRequestInterceptor); this.addResponseInterceptor(new TLHttpResponseInterceptor
(tlHttpRequestInterceptor));
}
}
Extend org.apache.http.HttpRequestInterceptor:
This class is used to inject session id as a cookie and additional headers that the
IBM Tealeaf system uses.
Chapter 1. Tealeaf installation and implementation in an Android application
67
import java.io.IOException; import java.util.Map.Entry; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.protocol.HttpContext; import android.webkit.CookieManager; import com.tl.uic.Tealeaf; import com.tl.uic.util.LogInternal;
/**
* @author ohernandez
*/ public class TLHttpRequestInterceptor implements HttpRequestInterceptor { private String url; private final String sessionId;
/**
* Constructor.
*/ public TLHttpRequestInterceptor() { super(); this.sessionId = null;
}
/**
* Constructor.
* @param sessionId Tealeaf session id.
*/ public TLHttpRequestInterceptor(final String sessionId) { this.sessionId = sessionId;
}
/**
* Get url of the request.
* @return Url of the request.
*/ public final String getUrl() { return url;
}
/**
* Url of the request.
* @param url Url of the request.
*/ public final void setUrl(final String url) { this.url = url;
}
/**
* {@inheritDoc}
*/ public final void process(final HttpRequest request, final
HttpContext context) throws HttpException, IOException { try { this.url = request.getRequestLine().getUri(); if (!request.containsHeader(Tealeaf.TLF_HEADER)) { request.addHeader(Tealeaf.TLF_HEADER, "device (Android) Lib/"
+ Tealeaf.getLibraryVersion());
} if (!request.containsHeader(Tealeaf.TLF_PROPERTY_HEADER)) { request.addHeader(Tealeaf.TLF_PROPERTY_HEADER,
68
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
Tealeaf.getHttpXTealeafProperty());
} if (Tealeaf.getAdditionalHeaders() != null) { for (final EntryString,<String> entry :
Tealeaf.getAdditionalHeaders().entrySet()) { request.addHeader(entry.getKey(), entry.getValue());
}
} final StringBuffer cookies = new StringBuffer(Tealeaf.
getTLCookie(this.sessionId)); if (this.getUrl() != null) { final String extistingCookies = CookieManager.getInstance().
getCookie(this.getUrl()); if (extistingCookies != null) { cookies.append(’;’); cookies.append(extistingCookies);
}
}
}catch (final Exception e) {
Tealeaf.logException(e);
} request.addHeader("Cookie", cookies.toString());
LogInternal.log("Session cookie:" + cookies.toString());
}
}
Extend org.apache.http.HttpResponseInterceptor:
This class is used to get information to fill out a IBM Tealeaf connection object.
import java.io.IOException; import java.util.Date; import org.apache.http.HttpException; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.protocol.HttpContext; import com.tl.uic.TLFCache; import com.tl.uic.Tealeaf; import com.tl.uic.util.LogInternal;
/**
* @author ohernandez
*
*/ public class TLHttpResponseInterceptor implements HttpResponseInterceptor { private final TLHttpRequestInterceptor tlHttpRequestInterceptor; private final Date startTime; private final long initTime;
/**
* Constructor.
*
* @param tlHttpRequestInterceptor TLHttpRequestInterceptor used.
*/ public TLHttpResponseInterceptor(final TLHttpRequestInterceptor tlHttpRequestInterceptor) { this.tlHttpRequestInterceptor = tlHttpRequestInterceptor; this.startTime = new Date(); this.initTime = TLFCache.timestampFromSession();
}
/**
Chapter 1. Tealeaf installation and implementation in an Android application
69
* {@inheritDoc}
*/ public final void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { try { final Date endTime = new Date(); final Date startLoad = new Date(); final long loadTime = (new Date()).getTime() - startLoad.getTime(); this.initTime, loadTime, responseTime);
} catch (final Exception e) {
LogInternal.logException(e);
} final long responseTime = endTime.getTime() - this.startTime.getTime();
Tealeaf.logConnection(this.tlHttpRequestInterceptor.getUrl(), response,
}
}
Uses non IBM Tealeaf session ID
You must get your generated session ID and use it when you enable or start a new session in Android SDK.
// If enabling of Android Logging Framework use
Tealeaf.enable();
Tealeaf.enable("your session id");
// If Android Logging Framework is enabled and a new session is to be created use
Tealeaf.startSession();
Tealeaf.startSession("your session id");
Android application gestures
You can capture gestures that the users make on your Android application. Several types of gestures are captured.
Configuration
For any Activity class that you want Gesture logging, you edit
TLFConfigurableItems.properties
file and set the SetGestureDetector property to true .
Touch event methods
You add your variables to one of these methods: v onTouchEvent - use this method if your activity is not using a customized gesture view.
v dispatchTouchEvent - use this method if your activity is using a customized gesture view.
If your application uses a customized gesture view, onTouchEvent does not detect the gestures because they are already captured by the customized gesture view. If you are using a customized gesture view, you must use dispatchTouchEvent.
You can use either the onTouchEvent or the dispatchTouchEvent. If you use both, the gestures are captured twice.
Gesture events captured:
Gestures that are used to select items in an application or to adjust views in the application are captured by Tealeaf.
70
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
Tap gestures
This table lists and describes the tap gestures that are captured from web and mobile apps.
Note:
The arrows that illustrate the direction of a swipe or pinch gesture are not supported by the Internet Explorer browser.
Table 5. Tap gestures.
Gesture name Description Image displayed in Replay
Tap This gesture is a one-finger gesture.
For a tap gesture, one-finger taps and lifts from the screen in 1 location.
Tap and Hold This gesture is a one-finger gesture.
For a Tap and Hold gesture, one-finger presses and stays on the screen until information is displayed or an action occurs.
Note:
The response to a Tap and Hold gesture can vary from one application to another. For example, a Tap and Hold gesture might display an information bubble, magnify content under the finger, or present the user with a context menu.
Double tap This gesture is a one-finger gesture.
For a double tap gesture, one-finger taps twice in close succession in 1 location of the screen.
Swipe gestures
This table lists and describes the swipe gestures that are captured from web and mobile apps:
Chapter 1. Tealeaf installation and implementation in an Android application
71
Table 6. Swipe gestures
Gesture name Description
Swipe vertically
Swipe horizontally
This gesture is a one-finger gesture.
For a swipe vertically gesture, one-finger:
1.
taps and holds in 1 location of screen,
2.
continues to engage screen while it moves up or down
3.
lifts from the screen in different location.
Note:
The initial tap becomes lighter in color, while the destination is highlighted by a darker color
This gesture is a one-finger gesture.
For a swipe horizontally gesture, one-finger:
1.
taps and holds in 1 location of screen,
2.
continues to engage screen while it moves left or right
3.
lifts from the screen in different location.
Note:
The initial tap becomes lighter in color, while the destination is highlighted by a darker color
Image displayed in Replay
Resize gestures
This table lists and describes the resize gestures that are captured from web and mobile apps:
Note:
See the IBM Tealeaf Customer Experience 9.0.1 Release Notes for information about a known limitation for handling some iOS pinch gestures.
Table 7. Resize gestures
Gesture name Description
Pinch open Sometimes referred to as a spread gesture, this is a two-finger gesture.
Image displayed in Replay
Pinch close
For a pinch open gesture, 2 fingers:
1.
tap and hold in 1 location of the screen,
2.
maintain contact with the screen while the fingers move apart from each other in any direction,
3.
lift from the screen at a new location.
This gesture is a two-finger gesture.
Note:
Accompanying arrows indicate the direction
(open or close) of the pinch
For a pinch close resize gesture, 2 fingers:
1.
tap and hold in 1 location on the screen,
2.
maintain contact with the screen while the fingers move toward each other,
3.
lift from the screen at a new location.
Note:
Accompanying arrows indicate the direction
(open or close) of the pinch
72
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
Unresponsive gesture events captured
Unresponsive gestures are gestures that do not respond when a user tries to select items in an application or tries to adjust views in the application. Like other gesture events, unresponsive gestures are captured by Tealeaf.
Unresponsive gestures are displayed graphically in BBR as orange outlined icons accompanied by a circled "X" . The circled "X" denotes that the gesture was unresponsive. For example, if a double tap gesture did not yield a response in the mobile application, then at replay time that gesture is displayed with the following icon in BBR:
The following table lists the unresponsive gestures that are captured from web and mobile apps and shows the images that are displayed in BBR:
Table 8. Unresponsive gestures and icons
Unresponsive Gesture
Tap gestures
Image displayed in Replay
Unresponsive tap
Unresponsive double tap
Unresponsive tap and hold
Swipe gestures
Chapter 1. Tealeaf installation and implementation in an Android application
73
Table 8. Unresponsive gestures and icons (continued)
Unresponsive Gesture
Tap gestures
Swipe vertically
Image displayed in Replay
Swipe horizontally
Note:
Accompanying arrows indicate the direction of the swipe.
Resize gestures
Pinch open
Note:
Accompanying arrows indicate the direction of the swipe.
Pinch close
Note:
Accompanying arrows indicate the direction of the pinch.
Note:
Accompanying arrows indicate the direction of the pinch.
Instrumenting your application for Android gestures:
You can enable your application to capture gestures that the user makes on your application. To enable gestures for an Activity class, you modify the Activity class.
74
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
For example, you modify the MainActivity.java file and call the
Tealeaf.dispatchTouchEvent method inside dispatchTouchEvent or onTouchEvent method.
To use the Android gestures module, you must the Android Support Library android-support-v4.jar
together with Tealeaf SDK uicandroid.jar. The android-support-v4.jar
is distributed within Android SDK. Download and install the Android Support Library from the Android Support Library site. The installation installs the android-support-v4.jar at ${your Android SDK location}/extras/android/support/v4/android-support-v4.ja
r
1.
Open the MainActivity.java file for your application.
2.
Override either the dispatchTouchEvent or the onTouchEvent method, depending on how you are using gestures in your application:
IF your application is...
using a customized gesture view not using a customized gesture view
THEN...
Override the dispatchTouchEvent publc boolean dispatchTouchEvent
( MotionEvent e) {
}
Tealeaf.dispatchTouchEvent(this, e); return super.dispatchTouchEvent(e);
Override the onTouchEvent publc boolean onTouchEvent
( MotionEvent e) {
Tealeaf.dispatchTouchEvent(this, e); return super.onTouchEvent(e);
}
This example shows the code snippets that are added in this task for an application that does not use a customized gesture view: mport com.tl.uic.Tealeaf; import com.tl.uic.app.UICActivity; import android.os.Bundle; import android.view.MotionEvent; public class MainActivity extends UICActivity{
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
Tealeaf.logScreenLayout(this, this.getLogicalPageName(), 1000);
}
} public boolean dispatchTouchEvent( MotionEvent e) {
Tealeaf.dispatchTouchEvent(this,e); return super.dispatchTouchEvent(e);
}
Modifying the TLFConfiguratbleItems.properties file for gestures:
After you define the variables for gestures in your Activity class, you enable gesture capture by modifying the TLFConfiguratableItems.properties file.
1.
Edit the TLFConfiguratableItems.properties file.
Chapter 1. Tealeaf installation and implementation in an Android application
75
2.
Set SetGestureDetector to true.
3.
Save and exit the TLFConfiguratableItems.properties file.
Log exceptions
Exceptions are the way that a system or framework communicates to the application that something is wrong. Tealeaf provides two mechanisms to log exceptions. You can manually log exceptions by using the logException API, or
Tealeaf SDK will automatically log uncaught exceptions. The exception information can be used for analytics.
Automatically log exceptions
When your application throws an uncaught exception, Tealeaf Android SDK records the stack trace and state of the device at the time the exception was thrown. Tealeaf Android SDK sends the crash information to your target servers for processing.
Manually log exceptions
In the Android SDK, you modify your catch block to report caught exceptions to the target server for processing. When you modify your catch block, you get the full stack trace and same device information that Tealeaf collects for fatal crashes.
This table shows the method that is used to log exceptions and describes the parameters that are used in the method:
Method
public static Boolean logException(final
Throwable exception, final
HashMap<String, String> data,
final Boolean unhandled)
Parameters
Where: v @param exception - the exception to be logged.
v @param data - the value to be given to event.
v
@param unhandled - whether the exception is unhandled.
v @return - whether exception was logged.
Example
In this example, you have a method that causes an exception: public void clientMethod1( ) {
}
You add an @try , @catch, and the Tealeaf.logException(e, data, false) method to handle the exception: public void clientMethod1( ) { try { int[] array = new int[1]; int i = array[2]; // Index out of bound exception
}
}
} Catch (Exception e) {
HashMap<String, String> data = new HashMap<String, String>(); data.put("extraMessage", "custom value1");
Tealeaf.logException(e, data, false);
76
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
Logging exceptions:
Use the examples in this task as a guide to adding exception logging to your application.
1.
Determine the method for which you want to log exceptions. For example, you have a method: public void clientMethod1( ) {
}
2.
Optional: Add the exception method to the method for which you want to log the exceptions.
Add @try , @catch, and the Tealeaf.logException(e, data, false) method to handle the exception: public void clientMethod1( ) { try { int[] array = new int[1]; int i = array[2]; // Index out of bound exception
}
} Catch (Exception e) {
HashMap<String, String> data = new HashMap<String, String>();
}
Tealeaf.logException(e, data, false);
Hybrid applications
An application is considered to be hybrid if it contains a WebView in the Android application.
If you use a WebView, you must use UICWebView to log request activity in the
WebView. UICWebView extends the base WebView from the Android Framework, which inserts the IBM Tealeaf header with the current session ID for sessionization.
If you decide not to use UICWebView, then you need to extend a Webview to add sessionization.
See "UICWebView Class" in the IBM Tealeaf Android SDK Guide.
Extend android.webkit.WebView:
This sample code shows how the base Android WebView is extended with
UICWebView .
/*******************************************************************************
* Licensed Materials - Property of IBM
* (C) Copyright IBM Corp. 2015
* US Government Users Restricted Rights - Use, duplication or disclosure
* restricted by GSA ADP Schedule Contract with IBM Corp.
******************************************************************************/ package com.tl.uic.webkit; import java.util.Date; import java.util.Map; import org.apache.http.HttpResponse; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.util.AttributeSet; import android.webkit.WebView; import com.tl.uic.TLFCache; import com.tl.uic.Tealeaf;
Chapter 1. Tealeaf installation and implementation in an Android application
77
import com.tl.uic.javascript.JavaScriptInterface; import com.tl.uic.model.PropertyName;
/**
* @author ohernandezltmac
*/ public class UICWebView extends WebView { private Date endLoad; private Date startLoad; private String url; private HttpResponse httpResponse; private Date initTime; private long responseTime; private long connectionInitFromSession; private PropertyName webViewId;
/**
* @param context Android context.
*/ public UICWebView(final Context context) { super(context); init();
}
/**
* @param context Android context.
* @param attrs an AttributeSet passed to our parent.
*/ public UICWebView(final Context context, final AttributeSet attrs) { super(context, attrs); init();
}
/**
* @param context Android context.
* @param attrs an AttributeSet passed to our parent.
* @param defStyle the default style resource ID.
*/ public UICWebView(final Context context, final AttributeSet attrs, final int defStyle) { super(context, attrs, defStyle); init();
}
/**
* When page finished loading.
*
* @return When page finished loading.
*/ public final Date getEndLoad() { return endLoad;
}
/**
* When page finished loading.
*
* @param endLoad When page finished loading.
*/ public final void setEndLoad(final Date endLoad) { this.endLoad = endLoad;
}
/**
* When page starts loading.
*
* @return When page starts loading.
*/
78
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
public final Date getStartLoad() { return startLoad;
}
/**
* When page starts loading.
*
* @param startLoad When page starts loading.
*/ public final void setStartLoad(final Date startLoad) { this.startLoad = startLoad;
}
/**
* HttpResponse from the connection.
*
* @return HttpResponse from the connection.
*/ public final HttpResponse getHttpResponse() { return httpResponse;
}
/**
* HttpResponse from the connection.
*
* @param httpResponse HttpResponse from the connection.
*/ public final void setHttpResponse(final HttpResponse httpResponse) { this.httpResponse = httpResponse;
}
/**
* Initial time from the connection.
*
* @return Initial time from the connection.
*/ public final Date getInitTime() { return initTime;
}
/**
* Initial time from the connection.
*
* @param initTime Initial time from the connection.
*/ public final void setInitTime(final Date initTime) { this.initTime = initTime; this.connectionInitFromSession = TLFCache.timestampFromSession();
}
/**
* Response time from the connection.
*
* @return Response time from the connection.
*/ public final long getResponseTime() { return responseTime;
}
/**
* Response time from the connection.
*
* @param responseTime Response time from the connection.
*/ public final void setResponseTime(final long responseTime) { this.responseTime = responseTime;
}
Chapter 1. Tealeaf installation and implementation in an Android application
79
/**
* Get webview id.
*
* @return Webview id.
*/ public final PropertyName getWebViewId() { return webViewId;
}
/**
* Set webview id.
*
* @param webviewId Webview id.
*/ public final void setWebViewId(final PropertyName webviewId) { this.webViewId = webviewId;
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("PMD.NullAssignment")
@Override public void loadData(final String data, final String mimeType, final String encoding) { this.url = null; this.initTime = null; this.connectionInitFromSession = 0; this.responseTime = 0; this.httpResponse = null; this.startLoad = new Date(); super.loadDataWithBaseURL(this.url, data, mimeType, encoding, "");
}
/**
* {@inheritDoc}
*/
@SuppressLint("NewApi")
@Override public void loadUrl(final String url) { loadUrl(url, null);
}
/**
* {@inheritDoc}
*/ public final void loadUrl(final String url, final Map<String, String> extraHeaders) { this.url = url;
Tealeaf.setTLCookie(this.url); super.loadUrl(url, extraHeaders);
}
/**
* Initializes WebView.
*/ private void init() { setStartLoad(new Date());
// Need it when in Eclipse editor mode if (!this.isInEditMode()) { this.setWebViewClient(new UICWebViewClient()); this.setWebChromeClient(new UICWebChromeClient((Activity) this.getContext())); this.setWebViewId(Tealeaf.getPropertyName(this)); this.addJavascriptInterface(new JavaScriptInterface(this.getContext(), getWebViewId().getId()), "tlBridge");
80
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
}
}
/**
* Log the load time of the WebView.
*
* @return If log connection was added to queue.
*/ public final Boolean logConnection() { final long endTime = this.getEndLoad() != null ?
this.getEndLoad().getTime() : 0; final long startTime = this.getStartLoad() != null ?
this.getStartLoad().getTime() : 0; final long loadTime = endTime - startTime; return Tealeaf.logConnection(this.url, this.httpResponse, this.connectionInitFromSession, loadTime, this.responseTime);
}
}
Extend android.webkit.WebViewClient:
The sample code that follows extends the base Android WebViewClient with
UICWebViewClient .
/*******************************************************************************
* Licensed Materials - Property of IBM
* (C) Copyright IBM Corp. 2015
* US Government Users Restricted Rights - Use, duplication or disclosure
* restricted by GSA ADP Schedule Contract with IBM Corp.
******************************************************************************/ package com.tl.uic.webkit; import android.annotation.SuppressLint; import android.os.Build; import android.webkit.WebView; import android.webkit.WebViewClient;
/**
* @author ohernandezltmac
*
*/ public class UICWebViewClient extends WebViewClient {
/**
* {@inheritDoc}
*/
@Override public boolean shouldOverrideUrlLoading(final WebView view, final String url) { view.loadUrl(url); return true;
}
/**
* {@inheritDoc}
*/
@SuppressLint("NewApi")
@Override public void onPageFinished(final WebView view, final String url) {
// Get the call back mapping string to be evaluated/loaded as
Javascript code final String javascriptString = com.tl.uic.javascript.JavaScriptInterface.
hybridBridgeRegisterCallback(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { view.evaluateJavascript(javascriptString, null);
} else {
Chapter 1. Tealeaf installation and implementation in an Android application
81
view.loadUrl("javascript:" + javascriptString);
}
}
}
Sessionization for PhoneGap based Applications:
Since there are no requests and responses being sent back to the server, IBM
Tealeaf does not require extending of WebView to add sessionization.
Configuring DOM Capture and Replay for Native Android applications that cannot use PCA:
You configure DOM capture for a Native iOS application that cannot use PCA by modifying the defaultconfiguration.js file. If the HTML page in the webview does not fire on page load or if the page changes dramatically, you need to fire
DOM capture from within your Native Android application.
Before you do this task you must install the UIC library in your native application.
All of the modifications that you make are in your Native Android application.
1.
Modify the defaultconfiguration.js file and set the DOM Capture options that you want to use: replay: {
// DOM Capture configuration domCapture: { enabled: true,
// Filter object for matching rules is similar to the Privacy configuration
// It accepts a mandatory "event" followed by one or more optional targets
// as well as an optional delay after which to take the DOM snapshot.
triggers: [
{ event: "load" options: { captureFrames: true, // Should child frames/iframes be captured removeScripts: true // Should script tags be removed from the captured snaphot
}
}
}
],
// DOM Capture options
}
2.
If DOM Capture does not fire on load, set DOM Capture to fire from your application by adding this code to your Native Android application for the screenview that you want to capture: if (TLT === undefined) { console.log(’TLT is undefined!’);
} else { if (TLT.logScreenviewLoad === undefined) { console.log(’Could not invoke TLT.logScreenviewLoad API!’);
} else {
TLT.logScreenviewLoad("root"); console.log(’logScreenviewLoad:’);
} if (TLT.logDOMCapture === undefined) { console.log(’Could not invoke TLT.logDOMCapture API!’);
} else {
82
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
dcid = TLT.logDOMCapture(window.document, {}); console.log(’logDOMCapture:’ + dcid);
}
}
Hybrid application bridge for Android APIs:
An Android hybrid application is a native application that uses WebView control as part of the UI components. Tealeaf Android SDK provides JavaScript interface
APIs integrated with CX UI Capture j2, which can be started from JavaScript functions to access native methods in hybrid application.
Tealeaf Android SDK APIs available to JavaScript
When you develop hybrid applications, you embed WebView component within a larger Android application. You can access exposed Android native methods from the UI Capture j2 global JavaScript object called "TLT" with methods that you use in your JavaScript code. This table lists and gives examples of the methods that you can include in your JavaScript code:
Method
Enable Tealeaf Framework
Disable Tealeaf Framework
Log Screen Capture
Start New Tealeaf Session
Current Session ID
Example
/**
* Public API to enable Tealeaf framework.
* @returns {void}
*/ enableTealeafFramework();
/**
* Public API to disable Tealeaf framework.
* @returns {void}
*/ disableTealeafFramework();
/**
* Public API to add a screenshot capture.
* @returns {void}
*/ logScreenCapture();
/**
* Public API to start a new Tealeaf session.
* @returns {void}
*/ startNewTLFSession();
/**
* Public API to start get current
Tealeaf session Id.
* @returns {String} Current session
Id
*/ currentSessionId();
Chapter 1. Tealeaf installation and implementation in an Android application
83
Method
Default Value for Configurable Item
Value for Configurable Item
Set Configurable Item
Add Additional HTTP Header
Log Custom Event Bridge
Example
/**
* Public API to get default value of a configurable item in
* TLFConfigurableItems.properties
file.
* @param {String} configItem This is the name of the configurable item.
* @returns {String} The value for the item.
*/ defaultValueForConfigurableItem
(configItem);
/**
* Public API to get the value of a configurable item either from
* TLFConfigurableItems.properties
file
* or in memory data structure.
* @param {String} configItem This is the name of the configurable item.
* @returns {String} The value for the item.
*/ valueForConfigurableItem(configItem);
/**
* Public API to set the value of a configurable item in
TLFConfigurableItems.properties
* file.
* @param {String} configItem This is the name of the configurable item.
* @param {String} value The value assign to the configItem.
* @returns {boolean} Wether item was set.
*/ setConfigurableItem(configItem, value);
/**
* Public API to add additional http header.
* @param {String} key This is the key of the configurable item.
* @param {String} value The value assign to the configItem.
* @returns {boolean} Wether item was set.
*/ addAdditionalHttpHeader(key, value);
/**
* Public API to log custom event.
* @param {String} eventName A custom event name.
* @param {String} jsonData JSON data string.
* @param {int} logLevel Tealeaf library logging level for the event.
* @returns {boolean} Wether item was set.
*/ logCustomEventBridge(eventName, jsonData, logLevel);
84
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
Example of how a native Android API is started
This example shows how to start a native method to enable Tealeaf Framework on a UI Capture j2 "TLT" instance using JavaScript:
<script type="text/javascript">
// Example of calling the native API to enable Tealeaf Framework using Javascript
TLT.enableTealeafFramework();
</script>
Sample test HTML file that starts supported native methods in JavaScript
This example is an HTML file that starts supported native methods in JavaScript:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<script type="text/javascript" src="js/tealeaf.js"></script>
<script type="text/javascript" src="js/defaultconfiguration.js" ></script>
<title>test APIs</title>
<body>
<h2>Test page for Android bridge APIs in hybrid app</h2>
<h3>Click on below buttons to run tests:</h3>
<input type="button" style="width: 150px; height: 30px; font-size: 20px" value="Screen Capture" onclick="TLT.logScreenCapture();return false;"/>
<input type="button" style="width: 150px; height: 30px; font-size: 20px" value="Native APIs" onclick="runBridgeNativeTealeafAPIs();return false;"/>
<p/>
<p>Test native APIs output here:
<div id="queueData"></div>
</body>
<script type="text/javascript"> function htmlConsoleLog(textData, apiRetVal){ var para = document.createElement("p"); var node; if( apiRetVal !== undefined && apiRetVal !== null )
{
} else
{ node = document.createTextNode(textData + " returned: " + apiRetVal); node = document.createTextNode(textData );
} para.appendChild(node); var element = document.getElementById("queueData"); element.appendChild(para);
} function runBridgeNativeTealeafAPIs() { htmlConsoleLog( ’----- -------------------------------- -----’ ); htmlConsoleLog( ’----- Calling Tealeaf native APIs -----’ ); var apiRetVal = null; htmlConsoleLog( ’----- Calling enableTealeaf -----’ );
TLT.enableTealeafFramework(); apiRetVal = null; htmlConsoleLog( ’----- Calling currentSessionId -----’ ); apiRetVal = TLT.currentSessionId(); htmlConsoleLog( ’----- currentSessionId -----’, apiRetVal ); apiRetVal = null;
Chapter 1. Tealeaf installation and implementation in an Android application
85
htmlConsoleLog( ’----- Calling disableTealeaf -----’ );
TLT.disableTealeafFramework(); var apiRetVal = null; htmlConsoleLog( ’----- Calling enableTealeaf -----’ );
TLT.enableTealeafFramework(); apiRetVal = null; htmlConsoleLog( ’----- Calling currentSessionId -----’ ); apiRetVal = TLT.currentSessionId(); htmlConsoleLog( ’----- currentSessionId -----’, apiRetVal ); apiRetVal = null; htmlConsoleLog( ’----- Calling defaultValueForConfigurableItem
(PostMessageUrl) -----’ ); var PostMessageUrlVal = TLT.defaultValueForConfigurableItem
(’PostMessageUrl’); htmlConsoleLog( ’----- defaultValueForConfigurableItem -----’,
PostMessageUrlVal ); apiRetVal = null; htmlConsoleLog( ’----- Calling setConfigurableItem("PostMessageUrl",
"aValidPostUrl") -----’ ); apiRetVal = TLT.setConfigurableItem(’PostMessageUrl’, ’aValidPostUrl’); htmlConsoleLog( ’----- setConfigurableItem -----’, apiRetVal ); apiRetVal = null; htmlConsoleLog( ’----- Calling valueForConfigurableItem
("PostMessageUrl") -----’ ); apiRetVal = TLT.valueForConfigurableItem(’PostMessageUrl’); htmlConsoleLog( ’----- valueForConfigurableItem -----’, apiRetVal ); apiRetVal = null; htmlConsoleLog( ’----- Calling setConfigurableItem(PostMessageUrl,
’ + PostMessageUrlVal + ’) -----’ ); apiRetVal = TLT.setConfigurableItem(’PostMessageUrl’, PostMessageUrlVal ); htmlConsoleLog( ’----- setConfigurableItem -----’, apiRetVal ); apiRetVal = null; htmlConsoleLog( ’----- Calling valueForConfigurableItem
("PostMessageUrl") -----’ ); apiRetVal = TLT.valueForConfigurableItem(’PostMessageUrl’); htmlConsoleLog( ’----- valueForConfigurableItem -----’, apiRetVal ); apiRetVal = null; htmlConsoleLog( ’----- Calling startNewTLFSession -----’ ); apiRetVal = TLT.startNewTLFSession(); htmlConsoleLog( ’----- startNewTLFSession -----’, apiRetVal ); apiRetVal = null; htmlConsoleLog( ’----- Calling addAdditionalHttpHeader -----’ );
TLT.addAdditionalHttpHeader(’HeaderFromJavaScript’,
’HeaderValueFromJavaScript’); htmlConsoleLog( ’----- addAdditionalHttpHeader -----’ ); apiRetVal = null; htmlConsoleLog( ’----- Calling enableTealeaf again -----’ );
TLT.enableTealeafFramework(); apiRetVal = null; htmlConsoleLog( ’----- Calling currentSessionId -----’ ); apiRetVal = TLT.currentSessionId(); htmlConsoleLog( ’----- currentSessionId -----’, apiRetVal ); apiRetVal = null; var str = ’{\’key1AndroidBridge\’: \’value1AndroidBridge\’,
\’key2AndroidBridge\’: \’value2AndroidBridge\’}’;
86
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
htmlConsoleLog( ’----- Calling logCustomEvent("Test Android Bridge Custom
Event",’ + str +’) -----’ ); apiRetVal = TLT.logCustomEventBridge(’Test Android Bridge Custom Event’, str, 0); htmlConsoleLog( ’----- logCustomEvent(Test Android Bridge Event, ’ + str +’ ) -----’, apiRetVal ); htmlConsoleLog( ’----- Done Calling Tealeaf native APIs -----’ ); htmlConsoleLog( ’----- -------------------------------- -----’ ); htmlConsoleLog( ’----- -------------------------------- -----’ ); htmlConsoleLog( ’----- -------------------------------- -----’ );
}
</script>
</head>
</html>
Accessing native Android methods with JavaScript with Tealeaf customized WebView:
When you crate hybrid applications, you can access native Android methods with
JavaScript, you use the Tealeaf customized WebView.
Before you begin this task, you must:
1.
Install the most recent Tealeaf Android SDK.
2.
Implement the Android SDK following the instructions in the documentation.
3.
Include the most recent UI Capture j2 JavaScript source file.
1.
Add WebView to your application. Specify a length, height, weight, and ID that suits your application:
<WebView android:id="@+id/my_webview" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" />
2.
In your activity, locate the WebView and load your HTML file: public class MainActivity extends ActionBarActivity { private UICWebView mUICWebView; private String logicalPageName = "BridgeAppActivity";
@Override protected void onCreate(Bundle savedInstanceState) {
// Initialize tealeaf with a reference to application
Tealeaf tealeaf = new Tealeaf(this.getApplication()); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
// Load HTML file from local resource in the UICWebview mUICWebView = (UICWebView) findViewById(R.id.uic_webview);
// Modify the Url for your hybrid app mUICWebView.loadUrl("file:///android_asset/www/test.html");
WebSettings webSettings = mUICWebView.getSettings(); webSettings.setJavaScriptEnabled(true);
}
3.
Copy the application's HTML and JavaScript files to the /assets/www folder in your Android project.
Chapter 1. Tealeaf installation and implementation in an Android application
87
Quick start for server configuration
This section describes the basic steps to configure the IBM Tealeaf CX Passive
Capture Application and Windows based servers to capture and process data that is submitted from the Android SDK.
To enable processing of submitted data, you complete the steps in the following sections.
Target page for traffic capture
IBM Tealeaf is designed to capture traffic between a client and a web server. To facilitate capture, you must add a target page to your web server environment to which the Android SDK can submit posts.
You can use the same target page that is available for IBM Tealeaf CX UI Capture for AJAX.
See "UI Capture for Ajax Installation and Implementation" in the IBM Tealeaf CX UI
Capture for AJAX Guide.
After you add the target page to your web environment and enable the appropriate access permissions, you must configure the URL for the target page in the TLFConfigurableItems.properties page.
Note:
If needed, you can configure the client framework to submit by HTTPS by
adding the protocol identifier to the post URL. See Chapter 2, “Configuration file,” on page 95.
Traffic volume management
You can add a sampling function to work with the Android SDK KillSwitch. You can use this sampling function to throttle the sampling rate and thus the volume of traffic that is forwarded for capture.
For more information about sampling functions for various server environments, see "Sample Code" in the IBM Tealeaf Android SDK Guide.
CX Passive Capture Application traffic capture verification
You verify that the IBM Tealeaf CX Passive Capture Application in your IBM
Tealeaf environment is configured to capture and process the data that is submitted from the Logging Frameworks.
The data is submitted using specific content types, which the CX Passive Capture
Application is typically configured to capture by default. You must verify that these content types were enabled for capture through the CX Passive Capture
Application Web Console.
Note:
After the completion of the steps in this section, data is processed by IBM
Tealeaf.
Verifying CX Passive Capture Application capture type configuration
You use this procedure to verify that the CX Passive Capture Application is configured to capture the content types submitted by the Android SDK.
88
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
Note:
Depending on the version of the CX Passive Capture Application you installed, the required content types may already be configured for capture.
The Android SDK submits messages using the text/json content type.
Note:
Each IBM Tealeaf Logging Framework can use a different content type for submitting events for capture to IBM Tealeaf. Be sure to review and verify the content type for each deployed client framework.
1.
Log in to the CX Passive Capture Application web console:
<PCAServer>:8080 where
<PCAServer> is the host name of the CX Passive Capture Application server.
2.
Click the Pipeline tab.
3.
Click Edit Type Lists.
4.
In the Capture All POST Types box, verify that the following values ae included: text/json text/x-json application/json application/x-json
5.
Click Add.
6.
The CX Passive Capture Application is now configured to capture the required content types. All subsequent hits of this type are captured.
7.
Save changes.
See "PCA Web Console - Pipeline Tab" in the IBM TealeafCX Passive Capture
Application Manual.
Configuring CX Passive Capture Application for Logging
Framework screen captures
Optionally, you can enable the Android SDK to capture screen captures during the initial load of each view or screen of your web application. These screen captures are forwarded to the IBM Tealeaf Target Page in .PNG format for capture and use during session display.
See “UICActivity class” on page 105.
When this option is enabled, you must configure the CX Passive Capture
Application to capture these screen captures. By default, the CX Passive Capture
Application drops capture of binary or static content, so you must configure it to capture these images that are submitted as binary POSTs to the target page.
1.
Log in to the CX Passive Capture Application web console:
<PCAServer>:8080
Where
<PCAServer> is the host name of the CX Passive Capture Application server.
2.
Click the Pipeline tab.
3.
Click Edit Type Lists.
4.
In the Excluded File Extensions list, verify that png is listed.
5.
In the Included File Extensions list, verify that png is not listed.
Chapter 1. Tealeaf installation and implementation in an Android application
89
Note:
If a file extension is included in this list, then all instances that are sent as responses are captured, which greatly expands the volume of data that is captured by the CX Passive Capture Application. Capture in this manner is not required.
6.
In the Binary POST Types box, enter the following value: image/png
7.
Click Add.
8.
The image/png POST type is added and enabled for capture. This setting allows the PNG posts to be captured by the CX Passive Capture Application.
9.
Save changes.
See "PCA Web Console - Pipeline Tab" in the IBM Tealeaf CX Passive Capture
Application Manual.
Enabling automated extraction of compressed POSTs
The Android SDK automatically compresses POST data. You must configure the
CX Passive Capture Application to extract them.
Note:
For CX Passive Capture Application Build 3502 or later, this decompression is done automatically. If you are using one of these CX Passive Capture
Application builds, this configuration step is not necessary.
1.
In the CX Passive Capture Application Web Console, click the Pipeline tab.
2.
Select Inflate compressed requests and responses.
3.
Save changes.
The compress POSTs are now automatically extracted by the CX Passive Capture
Application and processed normally.
Options for monitoring captures and processing
You use different tools for testing your configuration and monitoring captures on an ongoing basis.
At target page
You can test the basic functionality of the target page by triggering GET and POST actions on the URL where the target page was installed.
See "UI Capture for Ajax Installation and Implementation" in the IBM Tealeaf CX UI
Capture for AJAX Guide.
In Windows pipeline
You can monitor the capture and processing of hits in the Windows pipeline in real time through the IBM Tealeaf Management System. See "TMS Pipeline Status Tab" in the IBM Tealeaf cxImpact Administration Manual.
Configuring sessionization for Android applications in IBM
Tealeaf
IBM Tealeaf provides multiple mechanisms for identifying and tracking individual visitor sessions. For the Android SDK, more configuration can be required.
Review the following steps and complete any necessary ones to sessionize your mobile application.
90
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
To enable sessionization of hits that are captured through the Android SDK, you must deploy the Sessioning session agent. See "Sessioning Session Agent" in the
IBM Tealeaf CX Configuration Manual
1.
Log in to the Portal as an administrator.
2.
From the Portal menu, select Tealeaf > TMS. The IBM Tealeaf Management
System opens.
See "Tealeaf Management System" in the IBM Tealeaf cxImpact Administration
Manual.
3.
Click the WorldView tab.
4.
For the View, select Servers.
See "TMS WorldView Tab" in the IBM Tealeaf cxImpact Administration Manual.
5.
Click the Transport Service node.
6.
Select Transport Service configuration. Then, click View/Edit.
7.
The Pipeline Editor opens.
Note:
Verify that the Sessioning session agent was installed.
v If it was not installed, drag it from the Available SessionAgents window to the pipeline.
v For more information about deploying it, see "TMS Pipeline Editor" in the
IBM Tealeaf cxImpact Administration Manual.
8.
Select the Sessioning session agent. Click Edit.
9.
In the Sessioning session agent configuration, modify the PrimarySessField value as follows:
PrimarySessField=AppEnv:SessionID,env:HTTP_X_TEALEAF
10.
Save the configuration file.
11.
Push the change to all servers. A restart is needed for the new sessionization keys to take effect.
Android view name as URL during replay
Errors that can occur during session replay can be resolved by using the Android view name as the URL during replay.
When you attempt to replay a session captured by the Android SDK, an error message can indicate that there are no viewable pages in the session. This error is related to the manner in which pages on Android devices are mapped.
Instead of displaying the URL during replay, you can configure IBM Tealeaf replay clients to show the Android view name instead, which eliminates this cosmetic error message.
To use the Android view name as the URL when you replay the session, complete the following steps to configure the appropriate replay profile rule.
Note:
Currently, configuration of this rule must be applied through the replay profile that is stored on the Replay Server. Instructions follow.
When this change is applied, the Navigable Pages list in Replay view in Browser
Based Replay and CX RealiTea Viewer is populated with the Android view name as the URL, instead of the generic IBM Tealeaf Target page URL.
v Browser Based Replay, or BBR
Chapter 1. Tealeaf installation and implementation in an Android application
91
This web-based replay client is accessible through the IBM Tealeaf Portal and retrieves its sessions through the Replay Server in your IBM Tealeaf environment.
– See "CX Browser Based Replay" in the IBM Tealeaf cxImpact User Manual.
– See "Configuring the Replay Server" in the IBM Tealeaf CX Configuration
Manual.
v IBM Tealeaf CX RealiTea Viewer, or RTV
This replay client is a stand-alone Windows application that must be installed separately on your desktop. Through CX RealiTea Viewer, you can search for and replay sessions that are stored in your IBM Tealeaf environment.
See the IBM Tealeaf CX RealiTea Viewer User Manual.
To change the replay profile, you can use these options.
v
“Applying the view name change locally”
You can apply the change locally through the IBM Tealeaf CX RealiTea Viewer, a desktop application for viewing and replaying events. You can use this option to test the change before you reconfigure the Replay Server.
v
“Applying the view name change to the Replay Server” on page 93
If you do not have access to CX RealiTea Viewer, you can change server settings.
Note:
CX RealiTea Viewer users must synchronize their local replay profiles to the server profile to acquire the change.
Applying the view name change locally:
Complete the following steps in CX RealiTea Viewer to make changes locally and test use of the Android view name during replay.
1.
Start the CX RealiTea Viewer application on your local desktop.
Note:
CX RealiTea Viewer must be installed locally on your Windows desktop. See "RealiTea Viewer (RTV) User Manual" in the IBM Tealeaf CX
RealiTea Viewer User Manual.
2.
Load a session that is captured from the Android SDK.
3.
From the CX RealiTea Viewer menu, select Tools > Options....
4.
Click the Profiles tab.
See "RealiTea Viewer - Profile Options" in the IBM Tealeaf CX RealiTea Viewer
User Manual.
5.
If you did not do so already, enter the name of the Replay Server that controls the replay profile in the Server check box. Click Check for Updates Now.
If a server version of the profile is available, your local version is synchronized to it.
6.
Click Edit Raw Profile.
7.
Complete the editing steps that are listed in the section that follows. You are
8.
After editing the profile as required, click Save Changes & Exit.
9.
Click OK.
10.
Replay the session. Click Replay in the toolbar.
11.
In the Navigable Pages list, the listed URLs reflect the Android view name for the screen.
92
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
12.
If the Navigable Pages list is being populated accurately, you can send your changes back to the Replay Server for deployment to other replay users.
a.
From the RTV menu, select Tools > Options.
b.
Click the Profiles tab.
c.
Click Upload Settings to Server.
Applying the view name change to the Replay Server:
Complete the following steps on the Replay Server so that all Browser Based
Replay users see the Android view name during replay.
In the following steps, you apply the change to the Replay Server by accessing the server and editing the appropriate file. This change is then available to all users of the Replay Server's profile, which includes all Browser Based Replay users.
1.
Log in to the server hosting the Replay Server as an administrator.
2.
Edit the following file:
<Tealeaf_install_directory>\system\ReplayServerProfile.xml
3.
Locate the RequestMapping section, which should be near the top of the file.
4.
Add a Request Mapping, URL element entry. Locate the following header:
<RequestEntry name="URL">
5.
Add the following key name as a new entry to the list of entries:
<Key name="HTTP_X_TEALEAF_VIEW_CLASS" enabled="1"/>
6.
Save the file.
Runtime configuration
As needed, you can change server-side settings from the client application. All configuration items can be configured dynamically from the client.
You can plan to manage server configuration during initialization of the application, then update it selectively and as needed during run time.
See "TeaLeaf Class" in the IBM Tealeaf Android SDK Guide.
Chapter 1. Tealeaf installation and implementation in an Android application
93
IBM Tealeaf events for Android SDK
The JSON format is used to track data that is captured by the Android SDK.
Data type
Description
Client Framework data (JSON)
If you are using step-based eventing, data from the client framework is submitted in JSON format and is available through Browser Based Replay for review and eventing. See "Step-Based Eventing" in the IBM Tealeaf Event
Manager Manual.
For a walk-through of how to capture this data into IBM Tealeaf events, see "Integrating Client Framework Data into Tealeaf" in the IBM Tealeaf
Client Framework Data Integration Guide.
Client Framework data (hit-splitting)
See “Client Framework versions supported in this documentation” on page
Upgrading the Android SDK
When you upgrade the IBM TealeafAndroid SDK, you complete the following general tasks.
Note:
Some steps can vary depending on your development and application environments.
1.
Review current requirements. See Minimum requirements.
2.
Review the package contents. See “Tealeaf package contents” on page 2.
3.
As an alternative to integrating the Android SDK with your application in development, you can use the sample application that is provided by IBM
Tealeaf. See “Tealeaf sample application” on page 3.
4.
Verify that your application environment is configured to meet the project requirements.
5.
Verify that the requirement code changes were applied. See “Android project changes” on page 4.
6.
Apply the basic configuration.
Note:
The latest version of the Android SDK includes new configuration
requirements. See “Basic configuration” on page 22.
7.
Verify that the appropriate content types are being captured and forwarded by
the IBM Tealeaf CX Passive Capture Application. See “CX Passive Capture
Application traffic capture verification” on page 88.
Note:
This step turns on the switch to begin capturing and processing data from the mobile application into Tealeaf. Depending on the volume of data,
you can use the kill switch. See “Traffic volume management” on page 88.
8.
Test your upgraded solution.
94
IBM Tealeaf Android SDK: IBM Tealeaf Android SDK Guide
Advertisement
Key Features
- Capture user interface and application events
- Collect data on how users interact with your application
- Improve user experience
- Optimize app performance
- Troubleshoot issues