AppSDK - Android guide Czech
last modification 26.3.2020 by Josef Vancura
Overview
The Nielsen SDK is one of multiple framework SDKs that Nielsen
provides to enable measuring linear (live) and on-demand TV viewing
using TVs, mobile devices, etc.
The App SDK is the framework for mobile application developers to
integrate Nielsen Measurement into their media player applications for
Android and iOS operating systems.
It supports a variety of Nielsen Measurement Products like Digital in TV Ratings, Digital Content Ratings (DCR, DTVR), Digital Ad Ratings (DAR), Digital Audio. This guide covers implementation steps for Android using Android Studio.
Prerequisites
To start using the App SDK, the following details are required:
- App ID (appid): Unique ID assigned to the player/site and configured by product.
If you do not have any of these prerequisites or if you have any questions, please contact our SDK sales support team - see Contact list for Czech Republic.
Step 1: Get SDK
For AppSDK versions, release dates and release notes - refer to Android AppSDK release notes.The Nielsen AppSDK can either be
-
integrated within an application through the use of Gradle - read Gradle implementation guide - Recommended solution that will keep your SDK copy latest after every build.
- For project with Android X use
implementation 'com.nielsenappsdk:globalx:+'
- For project with Android Support Libraries use
implementation 'com.nielsenappsdk:global:+'
- For project with Android X use
-
downloaded directly as jar file - download ZIP package at Nielsen Downloads.
Please accept licence, insert your contact details, select product "Digital Content Ratings (DCR)" and choose "Android SDK Download" in section "SDK Downloads".
Package contains appsdk.jar in 2 directories :
- "AndroidX" for usage with AndroidX projects
implementation files('libs/AndroidX/appsdk.jar')
- "Android" for usage with Android Support Libraries
implementation files('libs/Android/appsdk.jar')
- "AndroidX" for usage with AndroidX projects
Step 2: Setting up your Development Environment
Configuring Android Development Environment
1) (if using downloaded package) - Ensure to unzip the Nielsen App SDK sample app and copy the AppSdk.jar into the app/libs folder on the App’s project. Add it as dependency.
2) Add the following permissions on the project’s AndroidManifest.xml file.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
3) Add Google Play Services lib into dependencies as Nielsen AppSDK uses the following packages/classes from the Google Play service. Libraries:
- com.google.android.gms:play-services
Requiered Google Play Service CLasses and Packages :
- com.google.android.gms.ads.identifier.AdvertisingIdClient;
- com.google.android.gms.ads.identifier.AdvertisingIdClient.Info;
- com.google.android.gms.common.ConnectionResult;
- com.google.android.gms.common.GooglePlayServicesUtil;
- com.google.android.gms.common.GooglePlayServicesRepairableException;
- com.google.android.gms.common.GooglePlayServicesNotAvailableException;
4) In AndroidManifest.xml under <application> node add the following metadata
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version"/>
5) Once the files are in place, import com.nielsen.app.sdk to the java source code and start accessing the public interface.
import com.nielsen.app.sdk.*;
Notes:
- The Nielsen App SDK (located in the com.nielsen.app.sdk package) class is the primary application interface to the Nielsen App SDK on Android.
- The Nielsen App SDK class is defined as the only public class belonging to the com.nielsen.app.sdk package.
- Nielsen App SDK is compatible with Android OS versions 2.3+.
- Clients can control / configure the protocol to be used – HTTPS or HTTP to suit their needs.
- The Android OS hosting the App SDK should use a media player supporting HLS streaming (Android 3.0 and later will support it natively).
- If the player application uses a 3rd party media player implementing its own HLS, then the minimum Android version will be limited to version 2.3, since the SDK depends on Google Play support to work properly.
Step 3: SDK Initialization
The latest version of the Nielsen App SDK allows instantiating multiple instances of the SDK object, which can be used simultaneously without any issue. The sharedInstance API that creates a singleton object was deprecated prior to version 5.1.1. (Version 4.0 for Android)
- A maximum of four SDK instances per appid are supported. When a fifth SDK instance is launched, the SDK will return “nil” from initWithAppInfo:delegate:
- When four SDK instances exist, you must destroy an old instance before creating a new one.
The following table contains the list of arguments that can be passed via the AppInfo JSON schema.
Parameter / Argument | Description | Source | Required/Obligatory? | Example |
---|---|---|---|---|
appid | Unique id for the application assigned by Nielsen. It is GUID data type. | Nielsen-specified | ✓ | PXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX |
appname | Name of the application | Client-defined | No | Nielsen Sample App |
appversion | Current version of the app used | Client-defined | No | "1.0.2" |
sfcode | Nielsen collection facility to which the SDK should connect. Put "cz" (for both dev phase + testing and production) | Nielsen-specified | ✓ | "cz" |
nol_devDebug | Enables Nielsen console logging. Only required for testing | Nielsen-specified | Optional | "DEBUG" |
Sample SDK Initialization Code
1) AppSDK() is no longer a singleton object and should be initialized as below.
try{
// Prepare AppSdk configuration object (JSONObject)
JSONObject appSdkConfig = new JSONObject()
.put("appid", "PXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")
.put("appversion", "1.0")
.put("appname", "Sample App Name")
.put("sfcode", "cz")
.put("nol_devDebug", "DEBUG"); // only for debug builds
// Pass appSdkConfig to the AppSdk constructor
mAppSdk = new AppSdk(appContext, appSdkConfig, this);
}
catch (JSONException e){
Log.e(TAG, "Couldn’t prepare JSONObject for appSdkConfig", e);
}
2) implement IAppNotifier into your activity like
public class MainActivity extends AppCompatActivity implements IAppNotifier
3) implement callback
@Override
public void onAppSdkEvent(long timestamp, int code, String description){
Log.d(TAG, "SDK callback onAppSdkEvent " + description);
}
So whole Activity will look like
package com.example.josefvancura.nlsdemotmp;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.nielsen.app.sdk.*;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity implements IAppNotifier {
private AppSdk mAppSdk = null;
private String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Context context = getApplicationContext();
try{
// Prepare AppSdk configuration object (JSONObject)
JSONObject appSdkConfig = new JSONObject()
.put("appid", "PXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")
.put("appversion", "1.0")
.put("appname", "Sample App Name")
.put("sfcode", "cz")
.put("nol_devDebug", "DEBUG"); // only for debug builds
// Pass appSdkConfig to the AppSdk constructor
mAppSdk = new AppSdk(context, appSdkConfig, this ); // Notifier - activity implements IAppNotifier, callback in onAppSdkEvent()
}
catch (JSONException e){
Log.e(TAG, "Couldn’t prepare JSONObject for appSdkConfig", e);
}
}
@Override
public void onAppSdkEvent(long timestamp, int code, String description) {
Log.d(TAG, "SDK callback onAppSdkEvent " + description);
}
}
APP SDK Error & Event Codes
To view the Error and Event codes for iOS and Android, please review the App SDK Event Code Reference page.
Life cycle of SDK instance
Life cycle of SDK instance includes four general states:
- Initial state – The SDK is not initialized and hence, not ready to process playing information. Once the SDK is moved out of this state, it needs instantiation of the new SDK instance in order to get the instance in the Initial state.
- Idle state – The SDK is initialized and is ready to process playing information. Once Initialized, the SDK instance is not processing any data, but is listening for the play event to occur.
- Processing state – The SDK instance is processing playing information. API calls "play" and "loadMetadata" move the SDK instance into this state. In this state, the SDK instance will be able to process the API calls (see below)
- Disabled state – The SDK instance is disabled and is not
processing playing information. SDK instance moves into this state in
one of the following scenarios.
- Initialization fails
-
appDisableApi
is called
@property (assign) BOOL appDisableApi;
Step 4: Create Metadata Objects
The parameters passed must be either a JSON formatted string. The JSON passed in the SDK must be well-formed.
- JSON value must be string value.
- This includes boolean and numeric values. For example, a value of true should be represented with "true", number value 123 should be "123".
- All the Variable Names are case-sensitive. Use the correct variable name as specified in the documentation.
ChannelName metadata
channelName should remain constant throughout the completion of an episode or live stream.
Key | Description | Values | Required |
---|---|---|---|
channelName | Any string representing the channel/stream | custom | ✓ |
Content metadata
Content metadata should remain constant throughout the entirety of an episode/clip including when ads play. For detailed information of metadata and custom variables see specitication of Metadata for Czech Republic.
Ad Metadata
The ad metadata (if applicable) should be passed for each individual ad, if ads are available during or before the stream begins. For detailed information of metadata and custom variables see specitication of Metadata for Czech Republic.
MetaData Example
JSONObject channelInfo = new JSONObject()
.put("channelname","My Channel Name 1")
JSONObject contentMetadata = new JSONObject()
.put("assetid", "assetid_example")
.put("type", "content")
.put("program", "ProgramName")
.put("title", "Bunny in Woods")
.put("length", "579") // 9min 39sec
.put("mediaUrl", "") // empty
.put("airdate", "20171013 20:00:00")
.put("isfullepisode", "y")
.put("crossId1", "IDEC")
.put("nol_c1", "p1,") // empty for VOD
.put("nol_c2", "p2,TV ident")
.put("segB", "Program type")
.put("segC", "") // empty
.put("adloadtype", "1")
.put("hasAds", "1");
JSONObject adMetadata = new JSONObject()
.put("assetid", "assetid_example_postroll")
.put("type", "postroll")
.put("length", "30")
.put("title", "Nielsen postroll")
.put("nol_c4", "p4,ASMEAcode")
.put("nol_c5", "p5,AtributForAd")
.put("nol_c6", "p6,postroll");
Step 5: Configure API Calls
API Calls Types
play
The play method prepares the SDK for reporting once an asset has loaded and playback has begun. Use play to pass the channel descriptor information through channelName parameter when the user taps the Play button on the player. Call play only when initially starting the video.
mAppSdk.play(JSONObject channelInfo);
loadMetadata
Needs to be called at the beginning of each asset, pass JSON object for relevant content or ad. Make sure to pass as 1st loadMetadata for content at the begining of playlist - see below API call sequence examples.
mAppSdk.loadMetadata(JSONObject contentMetadata);
playheadPosition
Pass playhead position every second during playback. for VOD: pass current position in seconds. for Live: current UTC timestamp - if possible to seek back in Live content than pass related UTC time (not current). Pass whole number that increments only by 1 like 1,2,3..
mAppSdk.setPlayheadPosition(long videoPositon);
stop
Call when
- content or ads complete playing
- when a user pauses playback
- upon any user interruption scenario - see bellow chapter Interruption scenario
mAppSdk.stop();
end
Call when the content asset completes playback. Stops measurement progress.
mAppSdk.end();
API Call sequence
Use Case 1: Content has no Advertisements
Only content in playlist, A Sample API sequence follow this flow:
Playlist | Sample code | Description |
---|---|---|
1. Start of stream | play(channelName) |
channelName contains JSON metadata of channel/video name being played |
loadMetadata(contentMetadataObject) |
contentMetadataObject contains the JSON metadata for the content being played | |
2. Content | playheadPosition(position) |
playheadPosition is position of the playhead while the content is being played |
3. End of Stream | end |
Content playback is completed. |
Use Case 2: Content has Advertisements
Playlist : ad preroll - content - ad midroll - content continues - ad postroll.
The sample API sequence can be used as a reference to identify the
specific events that need to be called during content and ad playback.
Playlist | Sample code | Description |
---|---|---|
1. Start of stream | play(channelName); |
channelName contains JSON metadata of channel/video name being played |
loadMetadata(contentMetaDataObject); |
contentMetadataObject contains the JSON metadata for the content being played | |
2. Preroll | loadMetadata(prerollMetadataObject); |
prerollMetadataObject contains the JSON metadata for the preroll ad |
setPlayheadPosition(playheadPosition); |
position is position of the playhead while the preroll ad is being played | |
stop(); |
Call stop after preroll occurs | |
3. Content | loadMetadata(contentMetaDataObject); |
contentMetadataObject contains the JSON metadata for the content being played |
setPlayheadPosition(playheadPosition); |
position is position of the playhead while the content is being played | |
stop(); |
Call stop after the content is paused (ad starts) | |
4. Midroll | loadMetadata(midrollMetaDataObject); |
midrollMetadataObject contains the JSON metadata for the midroll ad |
setPlayheadPosition(playheadPosition); |
position is position of the playhead while the midroll ad is being played | |
stop(); |
Call stop after midroll occurs | |
5. Content (End) | loadMetadata(contentMetaDataObject); |
contentMetadataObject contains the JSON metadata for the content being played |
setPlayheadPosition(playheadPosition); |
position is position of the playhead while the content is being played | |
6. End of Stream | end(); |
Call end() at the end of content |
7. Postroll | loadMetadata(postrollMetaDataObject); |
postrollMetadataObject contains the JSON metadata for the postroll ad |
setPlayheadPosition(playheadPosition); |
position is position of the playhead while the postroll ad is being played | |
stop(); |
Call stop after postroll occurs |
Note: Each Ad playhead should reset or begin from 0 at ad start. When content has resumed following an ad break, playhead position must continue from where previous content segment was left off.
Step 6: Interruptions during playback
As part of integrating Nielsen App SDK with the player application, the Audio / Video app developer needs to handle the following possible interruption scenarios:
- Pause / Play
- Network Loss (Wi-Fi / Airplane / Cellular)
- Call Interrupt (SIM or Third party Skype / Hangout call)
- Alarm Interrupt
- Content Buffering continues for 30 seconds
- Device Lock / Unlock (Video players only, not for Audio players)
- App going in the Background/Foreground (Video players only, not for Audio players)
- Channel / Station Change Scenario
- Unplugging of headphone
In case of encountering one of the above interruptions, the player application needs to
- Call stop immediately (except when content is buffering) and withhold sending playhead position.
- once the playback resumes : start sending playheadPosition
Please see the Interruption Scenarios Page for more details
Handling Foreground and Background states
Foreground/Background state measurement is a requirement of Nielsen AppSDK implementation. It may be implemented in multiple ways for Android. Select one method from below :
a) Utilizing the Androidx LifeCycleObserver - RECOMMENDED, from SDK version 7.1.+
Starting with AppSDK version 7.1.0, with AndroidX support, an additional utility is provided in the AppSDK - application background/foreground state detection by the AppSdk leveraging the Android Architecture component "LifeCycleObserver". The AppSdk is now capable of detecting the application UI visibility state transitions between background and foreground, without forcing the applications to register for AppSdk's AppSdkApplication class, which is responsible for handling the detection of application background/foreground state transitions at present.
The following androidx dependency is required in the app gradle file:
implementation "androidx.lifecycle:lifecycle-extensions:2.1.0"'
b) ForeGround/Background Measurement via AndroidManifest
Add the following application tag to the Manifest XML. Integrating this into the Manifest XML will enable the SDK to measure app state directly. This approach requires that the application class is not in use for some other purpose.
<application android:name="com.nielsen.app.sdk.AppSdkApplication">
c) Using the Android SdkBgFbDetectionUtility Class
Using the SdkBgFgDetectionUtility class. You will need to copy/paste the code provided into a file.
d) Manual Background/ForeGround State Management
Manually identify the change of state through the application and call the respective API appInForeground() or appInBackground() to inform the SDK regarding the change of state from background to foreground or foreground to background.
The SDK is informed about app state using the below methods:
1. App going from Foreground to Background - call in onPause()mAppSdk.appInBackground(mContext);
mAppSdk.appInForeground(mContext);
Step 7: Privacy and Nielsen Opt-Out
A user can opt-out if they would prefer not to participate in any Nielsen online measurement research. To implement the opt-out option, include the following two items in your app settings screen or to your Privacy Policy / EULA section.
- A notice that the player includes proprietary measurement software that allows users to contribute to market research (such as Nielsen TV Ratings). The following paragraph is a template for an opt-out statement (in Czech).
Tato aplikace obsahuje proprietární měřící software spolecnosti Nielsen, která uživatélům umožní přispívat k průzkumu trhu. Chcete-li se dozvědet více o informacich, které může software Nielsen shromažďovat a o Vaši možnosti měření deaktivovat, prečtěte si zásady ochrany osobní údajů Nielsen Digital Measurement na Nielsen Digital Measurement Privacy Policy.
- A link to the Nielsen Digital Measurement Privacy Policy.
1. Get URL
URL for the Nielsen Privacy web page should be retrieved using below API method
mAppSdk.userOptOutURLString()
If the App SDK returns NULL in the optOutURL, handle the exception gracefully and retry later.
Example of returned Url is http://priv-policy.imrworldwide.com/priv/mobile/cz/cs/optout.html followed by unique hash.
2. Open URL in webView
Recieved URL should be opened in 'WebView' / External browser. App should provide a UI control like 'close' or 'back' button to close the 'WebView' / External browser.
3. Get current Opt-Out status (voluntarily)
To retrieve the current Opt-Out status of a device, use the API getOptOutStatus method.
mAppSdk.getOptOutStatus()
Put it inside AsyncTask to get proper result
Users can opt out or opt back into Nielsen Measurement. Current Opt-Out page have no hyperlinks for Opt-Out / Opt-In operations. SDK Opt-Out has to be done via Settings → Google → Ads → Opt out of Ads Personalization. User is opted out of Nielsen online measurement research when the "Opt out of Ads Personalization" setting is enabled.
Note: SDK will be sending the data pings to census even though SDK is opted out (In earlier releases all the traffic from SDK to census will be ceased). However, all the outgoing pings will have the parameter uoo=true using which backend can ignore this data.
Step 8: Test your player by your self
Test SDK API calls
to verify SDK API calls use LogCat console in Android Studio or adb (example of log).Test outgoing pings
Test setup :
1. Connect your PC and test device (tablet or phone) via same router.
2. Setup Proxy sw - example Charles Proxy (only for Android 6 and lower)
3. Test device: run your player, launch video
4. PC side: in proxy filter trafic by "imrworld" and confirm presence of GN pingsExample of GN ping
https://secure-cert.imrworldwide.com/cgi-bin/gn?prd=dcr&ci=cz-509218&ch=cz-509218_c04_P&asn=defChnAsset&sessionId=epHSOa1alCOKVx84Ghso0nyQbXiAL1558443517&tl=Nielsen%2520preroll&prv=1&c6=vc,c04&ca=cz-509218_c04_assetid_example_preroll&cg=ProgramName&c13=asid,P24E981D1-5A7F-471B-BB3A-9E8207A77B39&c32=segA,NA&c33=segB,Program%2520type&c34=segC,NA&c15=apn,CZ%20demo%20Artifactory&plugv=&playerv=&sup=1&segment2=-1&segment1=cze&forward=0&ad=1&cr=4_00_99_D1_00000&c9=devid,&enc=true&c1=nuid,&at=timer&rt=video&c16=sdkv,aa.6.0.0&c27=cln,27&crs=0&lat=&lon=&c29=plid,P24E981D1-5A7F-471B-BB3A-9E8207A77B39&c30=bldv,aa.6.2.0.0_ga&st=dcr&c7=osgrp,DROID&c8=devgrp,TAB&c10=plt,MBL&c40=adbid,&c14=osver,Android6.0.1&c26=dmap,1&dd=&hrd=&wkd=&c35=adrsid,&c36=cref1,IDEC&c37=cref2,&c11=agg,1&c12=apv,&c51=adl,27&c52=noad,1&sd=30&devtypid=asus-Nexus-7&pc=NA&c53=fef,n&c54=oad,&c55=cref3,&c57=adldf,2&ai=assetid_example_preroll&c3=st%252Ca&c64=starttm,1558443522&adid=assetid_example_preroll&c58=isLive,false&c59=sesid,JVThto0RdZkCNLXyA5TPa2DBNo0CO1558443522&c61=createtm,1558443552&c63=pipMode,&c60=cvarall,p0%252Cdcrcz~~~~~~st%252Ca~~p4%252CASMEAcode~~p5%252CAtributForAd~~p6%252Cpreroll&c62=sendTime,1558443552&c68=bndlid,cz.nielsenadmosphere.androiddemo&c69=cvw,&nodeTM=&logTM=&c73=phtype,Tablet&c74=dvcnm,Google+Nexus+7&c76=adbsnid,&df=-1&uoo=true&c44=progen,&davty=1&si=&c66=mediaurl,&vtoff=0&rnd=1558443552224
Step 9: Provide your app for certification
Once ready please send your application to Nielsen local staff for verification - see Contact list for Czech Republic.
Step 10: Going Live
After the integration has been certified (but not prior that), disable debug logging by deleting {nol_sdkDebug: 'DEBUG'} from initialization call - see Step 2.
Demos
see live demos with sample implementation available at at http://sdkdemo.admosphere.cz/
FAQ
1. When to instantiate Nielsen SDK ?
Answer: right at application start and only once during runtime.
2. Which API calls shall be executed and when ?
Answer : a) for standard runtime - please see Chapter 4 - API Call sequence b) for intertuption scenario - see Chapter 5 Interruptions during playback