Nielsen AppSDK

Android App Implementation

last update: 24.6.2021



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:

  • 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 Contacts.


Get the SDK

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:+'
  • 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 :
    • For project with Android X use
      implementation files('libs/AndroidX/appsdk.jar')
    • For project with Android Support Libraries use
      implementation files('libs/Android/appsdk.jar')
You will have to update SDK manually always when new version of AppSDK is released. Please keep your version of SDK up to date.


Step 1: Setting up your Android Development Environment

1) Ensure to unzip the Nielsen App SDK zip file 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 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 2: Create SDK Instance

The latest version of the Nielsen App SDK allows instantiating multiple instances of the SDK object when needed, which can then be used simultaneously. For the general use case where only one video is played at the same time in the App, a single instance of SDK object can then be used to play back and measure all watched streams one after another.:

The following table contains the list of arguments that can be passed via the AppInfo JSON schema.

Parameter Description Source Required Example
appid Unique id for the application assigned by Nielsen. It is GUID data type. Nielsen-specified Yes "PXXXXXXX-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 Yes "cz"
nol_devDebug Enables Nielsen console logging. Only required for testing CNielsen-specified Optional "DEBUG"

1) AppSDK() is no longer a singleton object and should be created as below.

        try{
            // Prepare AppSdk configuration object (JSONObject)
            JSONObject appSdkConfig = new JSONObject()
                    .put("appid", "PXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")
                    .put("appversion", "1.0.2")
                    .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", "PXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")
                    .put("appversion", "1.0")
                    .put("appname", "Sample App Name")
                    .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 3: Create Metadata Objects

The parameters passed must be either a JSON formatted string or a NSDictionary object. The JSON passed in the SDK must be well-formed.

  • NSDictionary object
    • If an object of unexpected type is passed to the method, the error message will be logged.
    • If string has invalid JSON format, the error message will be logged.
  • 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 like appid, appname, dataSrc, title, type etc. are case-sensitive. Use the correct variable name as specified in the documentation.
  • JSON string can be prepared using either raw NSString or serialized NSDictionary.


Create channelName Metadata

channelName should remain constant throughout the completion of an episode or live stream.

Key Description Values Reqired
channelName Any string representing the channel/stream custom yes


Create Content Metadata

Content metadata should remain constant throughout the completion of an episode / clip including the ads play.
See Specification of Metadata for Czech Republic.


Create Ad Metadata

The ad metadata should be passed for each individual ad.
See Specification 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 4: Start the Measurement


Overview of SDK API Calls


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 Unix timestamp (seconds since Jan-1-1970 UTC) - if it is possible to seek back in Live content, then pass related Unix time (not current). Pass whole number that increments only by 1 like 1,2,3..

                            mAppSdk.setPlayheadPosition(long videoPositon);

stop

Call when

  • 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();


Content Only

In order to start the measurement, follow the 3 first steps below for Content without Ads. When terminating the Content playback call end to terminate the Content Measurement for the given asset.

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 is playing playheadPosition(position) playheadPosition is position of the playhead while the content is being played
3. End of Stream end Content playback is completed.


Content with Ads

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


Step 5: Stop/Resume the Measurement for video Playback Interruptions

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
  • 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 headphones

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 pings playheadPosition for the new viewing session.

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:

  • App going from Foreground to Background - call in onPause()

    mAppSdk.appInBackground(mContext);
  • App is going from Background to Foreground - call in onResume()

    mAppSdk.appInForeground(mContext);


Step 6: Review SDK Integration Architecture Diagram


Step 7 : Disclose Nielsen Privacy Statement

The App SDK uses Mobile Ad IDs (Android ID or IDFA) which are fully hashed on the device before being sent to Nielsen (Nielsen never receives un-hashed values). Users retain the possibility to oppose the use of Mobile Ad IDs, or to reset them, by using the functionality provided by the mobile operating system (iOS or Android).

In order to disclose Nielsen measurement privacy statement, please include the following items in your privacy policy:

  • A notice that the player includes third party measurement software that allows users to contribute to market research with anonymous data.
  • A link to the Nielsen Digital Measurement Privacy Policy located at http://priv-policy.imrworldwide.com/priv/mobile/cz/cs/optout.html .


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 yourself


Guide

1. Connect your PC and test device (tablet or phone) via same router.

2. PC side: run Proxy sw (like Charles) and get local IP

3. Test device: modify Wifi setting to pass through Proxy IP from step 2.

4. Test device: run your player, launch video

5. PC side: filter traffic by "nmr" and confirm presence of GN pings


Example 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 Contacts.


Step 10 : Going Live

After the integration has been certified (but not prior that), disable debug logging by deleting {nol_devDebug: "DEBUG"} from initialization call - see Step 2.


Demos

See live demos with sample implementation available at http://sdkdemo.admosphere.cz/


Contacts

Company

Nielsen Admosphere

Českobratrská 2778/1

130 00 Praha 3

www.nielsen-admosphere.cz


Administration, testing, certification and technical support

Tomáš Kuchler

Technical Account Manager

+420 777 814 468

tomas.kuchler@admosphere.cz


NielsenSDK Team

SDKsupport@admosphere.cz


FAQ

When to instantiate Nielsen SDK?
Right at application start and only once during runtime.

Which API calls shall be executed and when?
a) for standard runtime - see Chapter 4
b) for intertuption scenario - see Chapter 5