Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Adding Telerik Analytics to Cordova Apps

DZone's Guide to

Adding Telerik Analytics to Cordova Apps

· Java Zone
Free Resource

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

Written by TJ VanToll


Adding Telerik Analytics to Cordova Apps

I recently setup Telerik Analytics on my City Search Challenge app, so I’ve spent the last few days looking at cool stats like these:

analytics-dashboard

In an effort to share what I learned from this experience, here’s a quick-and-dirty guide to getting Telerik Analytics running in your own apps.

Step 1: Install the plugin

Head to the analytics plugin’s page on the Verified Plugin Marketplace and click the appropriate “Instructions” link depending on your client of choice.

analytics-plugin

In my case I use the AppBuilder CLI, so I install the plugin with the following command:

$ appbuilder plugin add "Telerik Analytics"

Step 2: Add the analytics script

After you install the Cordova plugin, you must add a bit of JavaScript to setup the analytics monitoring itself. The Telerik Analtyics docs provide sample code blocks, but I prefer to use my own version that has a few small additions, which we’ll discuss momentarily. First here’s the code:

(function() {
// You'll need to insert your own custom values for these variables,
// and you'll get those values in steps 3 and 4.
var projectKey = "%ProjectKey%",
version = "%BundleVersion%";




window.analytics = {
start: function() {
var factory = window.plugins.EqatecAnalytics.Factory,
monitor = window.plugins.EqatecAnalytics.Monitor,
settings = factory.CreateSettings( projectKey, version );




settings.LoggingInterface = factory.CreateTraceLogger();
factory.CreateMonitorWithSettings( settings,
function() {
console.log( "Monitor created" );
monitor.Start(function() {
console.log( "Monitor started" );
});
},
function( msg ) {
console.log( "Error creating monitor: " + msg );
});
},
stop: function() {
var monitor = window.plugins.EqatecAnalytics.Monitor;
monitor.Stop();
},
monitor: function() {
return window.plugins.EqatecAnalytics.Monitor;
}
};




document.addEventListener( "deviceready", function() {
window.analytics.start();
document.addEventListener( "pause", function() {
window.analytics.stop();
});
document.addEventListener( "resume", function() {
window.analytics.start();
});
});
window.onerror = function( message, url, lineNumber, columnNumber, error ) {
window.analytics.monitor().TrackExceptionMessage( error, message );
};
}());

I take this file, save it as analytics.js, and include it in my project’sindex.html file.

<script src="analytics.js"></script>

The only difference between the documentation-provided code snippet and mine is the code at the bottom, specifically this chunk:

document.addEventListener( "deviceready", function() {
window.analytics.start();
document.addEventListener( "pause", function() {
window.analytics.stop();
});
document.addEventListener( "resume", function() {
window.analytics.start();
});
});
window.onerror = function( message, url, lineNumber, columnNumber, error ) {
window.analytics.monitor().TrackExceptionMessage( error, message );
};

The three addEventListener() calls listen for the Cordova lifecycle events, and start/stop the analytics monitoring appropriately. You may choose to start/stop analytics in a different part of your app, but I like keeping this code consolidated in a single analytics.js file.

The window.onerror function sets up a global JavaScript error handler. In this case, the handler calls the analytics plugin’sTrackExceptionMessage() method to log the exception, including valuable stack traces that you can use for debugging later.

To see where those errors are logged to, and to figure out how to replace that "%ProductKey%" string in the analytics script, you need to create an analytics project in the Telerik Platform.

Step 3: Create an analytics project

Head into your Telerik Platform account at https://platform.telerik.com and into the workspace that your app resides in. Next, click the big green “Create Analytics Project” button.

analytics-create-project

On the next screen select “AppBuilder” as a project type, give your project a name, and then click “Create project”:

analytics-configure-project

This takes you to the analytics dashboard, which is currently empty as you don’t have any data yet. To get analytics up and running you need to get your project key, which you can get from the options page.

analytics-new-dashboard

Grab the project key and copy it to your clipboard, as you’ll need it for the next step.

analytics-project-key

Step 4: Fill in the analytics.js variables

Now that you have a project in place, head back to your analytics.jsfile and find the two values that currently contain placeholder values:

var projectKey = "%ProjectKey%",
version = "%BundleVersion%";

The "%ProjectKey%" is the key you just copied from your Platform project, so go ahead and paste that in now.

The %BundleVersion% is the version of your application (1.0.0, 1.1.0, 2.0.0, and so forth). To replace that value you have two choices: you can hardcode the version (i.e. version = "1.0.0";), or you can dynamically retrieve the version number using the AppVersion plugin.

I recommend the AppVersion plugin, as I never remember to update hardcoded values, and because the AppVersion plugin is also a verified plugin with a super simple API. To install the AppVersion plugin you’ll want to refer to the Instructions links on the plugin’s page, shown below:

appversion-plugin

In my case I’m using the AppBuilder CLI, so I run the following command to install the plugin:

$ appbuilder plugin add "AppVersion"

With the plugin in place you run cordova.getAppVersion() to asynchronously retrieve the app version. For example, the following code alerts the version in a Cordova dialog:

cordova.getAppVersion(function( version ) {
navigator.notification.alert( "I'm version " + version );
});

To put everything together, here’s a copy-and-paste friendly version ofanalytics.js that you add to your apps:

(function() {
var version,
projectKey = "abcedfghijklmnopqrstuvwxyz1234"; // Replace with your own key




window.analytics = {
start: function() {
var factory = window.plugins.EqatecAnalytics.Factory,
monitor = window.plugins.EqatecAnalytics.Monitor,
settings = factory.CreateSettings( productId, version );




settings.LoggingInterface = factory.CreateTraceLogger();
factory.CreateMonitorWithSettings( settings,
function() {
console.log( "Monitor created" );
monitor.Start(function() {
console.log( "Monitor started" );
});
},
function( msg ) {
console.log( "Error creating monitor: " + msg );
});
},
stop: function() {
var monitor = window.plugins.EqatecAnalytics.Monitor;
monitor.Stop();
},
monitor: function() {
return window.plugins.EqatecAnalytics.Monitor;
}
};




// Guard against the AppBuilder simulator
// See tip #9 from http://developer.telerik.com/featured/20-kendo-ui-mobile-telerik-appbuilder-tips-tricks/
if ( navigator.simulator ) {
return;
}




document.addEventListener( "deviceready", function() {
cordova.getAppVersion(function( appVersion ) {
version = appVersion;
window.analytics.start();
document.addEventListener( "pause", function() {
window.analytics.stop();
});
document.addEventListener( "resume", function() {
window.analytics.start();
});
});
});
window.onerror = function( message, url, lineNumber, columnNumber, error ) {
window.analytics.monitor().TrackExceptionMessage( error, message );
};
}());

That’s it! With this code running you’re ready to head into your Telerik Analytics project and see your data pop up. Before you do though, make sure to heed this warning from the Analytics plugin’s documentation:

Once you’ve added the required code and deployed your app to a device, the first thing you’ll want to check is those nice graphs in your Telerik Analytics project. Make sure you switch to live mode to see the data as quickly as possible. It depends a bit on the platform and your internet connection how fast data pops up at the backend, so give it a few minutes before blaming your client-side code.

Personally I’ve found it usually takes ~3–4 minutes for my data to appear in live mode, but your experiences may vary.

(Optional) Step 5: Track features

Now that you have analytics installed, you can start utilizing its API, and that includes feature tracking. Telerik Analytics gives you a quick way of tracking what users do in your app. Want to know if users click that button you want to get rid of? Track it.

For example, suppose you have the following button in your app:

<button id="remove-image">Remove Image</button>

Assuming you’re using the analytics.js script from above, you can track clicks on this button with the following code:

document.querySelector( "#remove-image" ).addEventListener( "click", function() {
window.analytics.monitor().TrackFeature( "image.remove" );
});

The documentation for the TrackFeature() method recommends using dot-delimited feature names, as it makes features easier to aggregate. To give you an idea of why, here’s how this feature appears in an Analytics project after one use:

analytics-feature-use

Notice how the “image” portion of the string created a graph, and its subfeatures (currently just “remove”) appear as toggleable elements within the graph. This sort of setup is great for organizing numerous features, and also for A/B testing.

For added awesomeness, try using theTrackFeatureStart() andTrackFeatureStop() methods to time how long users are using certain features.

(Optional) Step 6: Explore your analytics project

Now that you have analytics installed, make sure to explore your backend to see all the data that’s available. Below I provide a few screenshots from my project to give you an idea.

The activity page tells you how many daily sessions your app has, what time of day those sessions occur on, and how long they are:

analytics-activity

The world map page visually displays the countries your app is used in:

analytics-world-map

The versions page tells you the versions of your app users actually use, and separates the data into iOS, Android, and Windows Phone segments automatically.

analytics-version

The environment page dives deeper and gives you information about your users’ operating systems, including what version of iOS/Android/Windows Phone they’re running, and the languages their devices use:

analytics-environment

The installations page tells you how many new users your app has, as well as how loyal your existing users are:

analytics-installations

The exceptions page aggregates all errors that have occurred in your app, including detailed stack traces. Remember the window.onerrorhandler that we setup earlier? This is where that data ends up.

analytics-exceptions

Wrapping up

There’s more, but I don’t want to take away all the surprises, as it’s fun to poke around and discover things for yourself. If you like what you see, or are just want to give Telerik Analytics a shot, you need to sign up for aTelerik Platform account, which includes a 30-day unlimited free trial. Looking to learn more? You may want to attend TelerikNEXT this May in Boston, where you can learn more about the Telerik Platform and the people behind it.

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

Topics:

Published at DZone with permission of Burke Holland, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}