DCR Italy Static Android SDK

From Engineering Client Portal

Revision as of 12:36, 11 May 2022 by WilsonQuispe (talk | contribs) (Implementation)

Engineering Portal breadcrumbArrow.png Digital breadcrumbArrow.png International DCR breadcrumbArrow.png DCR Italy Static Android SDK

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. It supports a variety of Nielsen Measurement Products like Digital in TV Ratings, Digital Content Ratings (DCR & DTVR), and Digital Ad Ratings (DAR). Nielsen SDKs are also equipped to measure static content and can track key life cycle events of an application like:

  • Application launch events and how long app was running
  • Time of viewing a page / sub section in the application.

Prerequisites

Before you start the integration, you will need:

Item Description Source
App ID (appid) Unique ID assigned to the player/site and configured by product. Provided by Nielsen
Nielsen SDK Includes SDK frameworks and sample implementation; See Android SDK Release Notes Download
sfcode Unique identifier for the environment that the SDK should point to Provided by Nielsen

If need App ID(s) or our SDKs, feel free to reach out to us and we will be happy to help you get started. Refer to Digital Measurement Onboarding guide for information on how to get a Nielsen App SDK and appid.

Implementation

This guide covers implementation steps for Android Studio utilizing the Standard Nielsen SDK for DCR.

How to obtain the NielsenAppApi

The Nielsen AppSDK can either be downloaded directly or can be integrated directly within an application through the use of Gradle. We recommend using the Gradle-based integration whenever possible to ensure you maintain the most recent changes and enhancements to the Nielsen libraries.

Setting up your Development Environment

Configuring Android Development Environment

  • The Nielsen App SDK (located in the Downloads section of the website) 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.
  • The Nielsen App SDK can also be added via Artifact Repository.

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 requirement for the Java AppSdk.jar library and the libAppSdk.so native library will depend on the type of host application that will make use of them.

  • For Video player applications
    • 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.

Once SDK is downloaded ensure to unzip the Nielsen SDK and copy the AppSdk.jar in your app (Android Studio) libs folder, then right click the AppSdk.jar and select Add As Library. Ensure the AppSdk.jar file is added in 'build.grade (App Level) file.

  • App SDK 1.2 provides support for x86, mips, and armeabi-7a architecture.

Google Play Services

Add the Google Play Services in the project, Steps: Android Studio -> File -> Project Structure ->(In module selection) select App -> Dependencies (tab) -> Click "+" button and search for "*play-services*". Then select the most recent version of the play-services Artifact. Ensure it is added in build.gradle (App level) file

The following is required if target API level is set to 31 (Android 12) with the Ad Version of the Nielsen SDK.

<uses-permission android:name="com.google.android.gms.permission.AD_ID"/>


Manifest File

  • 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"/>

For more details to handle runtime permissions in Android versions, please visit [1].

  • In AndroidManifest.xml under <application> add the following metadata
<meta-data 
android:name="com.google.android.gms.version" 
android:value="@integer/google_play_services_version"/>
  • App SDK checks to see if there is a Google service available and updated.
  • If not available or updated, App SDK will not use this service when executing its functions and will make reference to missing imports and the app will not be compiled.

Library

Nielsen App SDK uses the following packages/classes from the Google Play service.

  • google-play-services_lib

Classes/package

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

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)

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

  • The appid is provided by the Nielsen Technical Account Manager (TAM). The appid is a GUID data type and is specific to the application.
Parameter / Argument Description Source Required? Example
appid Unique Nielsen ID for the application. The ID is a GUID data type. If you did not receive your App ID, let us know and we will provide you. Nielsen-specified Yes PXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
appname Name of the application Client-defined Yes "Nielsen Sample App"
appversion Current version of the app used Client-defined Yes "1.0.2"
sfcode Nielsen collection facility to which the SDK should connect.

Italian Clients:

  • "it"
Nielsen-specified Yes "it"
nol_devDebug Enables Nielsen console logging. Only required for testing Nielsen-specified Yes for Debugging / Testing App "DEBUG"

Debug flag for development environment

Player application developers / integrators can use Debug flag to check whether an App SDK API call made is successful. To activate the Debug flag, Pass the argument @"nol_devDebug":@"DEBUG", in the JSON string . The permitted values are:

  • INFO: Displays the API calls and the input data from the application (validate player name, app ID, etc.). It can be used as certification Aid.
  • WARN: Indicates potential integration / configuration errors or SDK issues.
  • ERROR: Indicates important integration errors or non-recoverable SDK issues.
  • DEBUG: Debug logs, used by the developers to debug more complex issues.

Once the flag is active, it logs each API call made and the data passed. The log created by this flag is minimal.

Note: Activate the Debug flag in a Test environment.

Sample SDK Initialization Code

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

Initialization of App SDK object through a JSON object

  
try
{
  // Prepare AppSdk configuration object (JSONObject)
  JSONObject appSdkConfig = new JSONObject()
          .put("appid", "PDA7D5EE6-B1B8-4123-9277-2A788XXXXXXX")
          .put("appversion", "1.0.2")
          .put("appname", "Nielsen Sample App")
          .put("sfcode", "it")
          .put("nol_devDebug", "DEBUG"); // only for debug builds

// Pass appSdkConfig to the AppSdk constructor
mAppSdk = new AppSdk(appContext, appSdkConfig, appSdkListener);
}
catch (JSONException e)
{
  Log.e(TAG, "Couldn’t prepare JSONObject for appSdkConfig", e);
}


Here, appContext is the App context object and appSdkConfig is JSON object for holding the parameters (appid) the App passes to the Nielsen App SDK via a JSON string. The appid is obtained from Nielsen operational support and is unique to the app.


The integration of Nielsen App SDK will depend on type of client app.

  • Ensure that SDK files (AppSdk.jar and libAppSdk.so [App SDK 1.2 Only]) are included under the App’s project and the App SDK is linked to the App (the setting to link App SDK to the App can be found on property page of the App’s project).

APP SDK Error & Event Codes

To view the Error and Event codes for Android, please review the App SDK Event Code Reference page.

Configure Metadata

Handling JSON Metadata

All the SDK methods handles only two types of objects: NSString, NSDictionary. 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 Nielsen Key names (e.g. appid, program) 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.

Java

 JSONObject staticMetadata = new JSONObject()
        .put("type", "static")
        .put("section", "Home_EntityName_Android")
        .put("assetid", "vid345-67483")
    }

        //Sending metadata to SDK.
        mAppSdk.loadMetadata(staticMetadata);

The above code would be inserted only for the "home section" within your app.

Nielsen SDK Metadata

The following table defines the staticMetadata reserved keys:

Key Description Data Type Value Required?
type asset type fixed 'static' Yes
assetid Unique ID for each article dynamic custom (no Special Characters) Yes
section section of the App to be measured
EntityName = brand name or sub-brand name
dynamic Home_EntityName_Android for Android App Yes

Handling Foreground and Background states

There are a few approaches to managing the Foreground and Background states of an app available to use for state measurement.

  • Utilizing the Androidx LifeCycleObserver (The recommended approach starting sdk version 7.1.0.0+)
  • Utilizing the SdkBgFgDetectionUtility class
  • Adding a tag to the Manifest XML
  • Manual Management

The LifeCycleObserver

AndroidX replaces the original support library APIs with packages in the androidx namespace, and Android Studio 3.2 and higher provides an automated migration tool. (Select Refactor> Migrate to AndroidX from the menu bar.)

Starting with 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.

Please note, that if you already have an app designed that utilizes the depreciated SdkBgFgDetectionUtility Class, the AppSDK will ignore any calls to these methods if it can utilize the LifeCycleObserver. LifeCycleObserver based auto detection will take precedence.

Adding the AndroidX dependency

In order to make use of the app background/foreground state transition auto detection feature of AndroidX AppSdk, the app gradle file needs the androidx dependency. The AppSdk API calls - appInForeground() and appInBackground() will still be respected by AppSdk by executing the old AppSdk flow of handling "app in foreground" and "app in background" states as is.

Using the LifeCycle Extension

The following androidx dependency is required in the app gradle file:

implementation "androidx.lifecycle:lifecycle-extensions:2.1.0"

If you would like to take advantage of this auto detection feature of AppSdk at the very initial stage (e.g. splash screen or at of app launch time), before the AppSdk is initialized, can do so by calling the following newly introduced AppSdk public api, passing the application context :

public static void registerLifeCycleObserver(Context applicationContext)

Log messages for the new auto detection

  • When the AppSdk app successfully registers for the LifeCycleObserver : Registered LifeCycleObserver for App Background/Foreground auto-detection
  • When the app enters the foreground state :App is in foreground, auto detected by AppSDK
  • When the app enters the background state :App is in background, auto detected by AppSDK
  • If the client app doesn't have the "androidx" gradle dependency and AppSdk fails to register LifeCycleObserver :AndroidX LifecycleObserver can not be observed. Please use androidx dependency to activate SDK auto-detection of app background/foreground state.
  • When the appInForeground() is explicitly called while LifeCycleObserver auto detection is active :Ignoring the appInBackground() call, as the App Background/Foreground auto-detection is active. The current state is - foreground
  • When the appInBackground() is explicitly called while LifeCycleObserver auto detection is active :Ignoring the appInBackground() call, as the App Background/Foreground auto-detection is active. The current state is - background

The SdkBgFgDetectionUtility class

Foreground/Background state measurement is a requirement of Nielsen AppSDK implementation which is especially crucial for static measurement. It may be implemented in multiple ways for Android. This includes

  • Enable the Nielsen SDK to measure background/foreground state by makingthe relevant update to the AndroidManifest.
  • Integrate Nielsen’s SdkBgFgDetectionUtility class within your Custom Application Class.
  • Custom implementation of the required methods within your application.

ForeGround/Background Measurement via AndroidManifest

The simplest way to measure the app background/foreground state is to 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 is supported for Android 4.0 and up only; it requires that the application class is not in use for some other purpose.

 <application android:name="com.nielsen.app.sdk.AppSdkApplication">

Using the Android SdkBgFbDetectionUtility Class

For developers who are already using the application class, it is recommended that background/foreground state is implemented using the SdkBgFgDetectionUtility class. The SdkBgFgDetectionUtility class. is compatible with Android 4+ and has been made available to Nielsen clients. (You will need to copy/paste the code provided into a file).

Manual Background/ForeGround State Management

In cases where the developer is not able to use the AndroidManifest.xml solution nor the Nielsen provided SdkBgFgDetectionUtility class. the developer will need to 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.

AppLaunchMeasurementManager.appInForeground(getApplicationContext());
AppLaunchMeasurementManager.appInBackground(getApplicationContext());

Within the lifecycle of individual activities, onResume() and onPause() are best suited to providing indication of the app state.


Correct measurement of the foreground/background state is crucial to Static App measurement within Nielsen Digital Content Ratings (DCR).

Privacy and Opt-Out

There are two primary methods for implementing user Opt-out preferences:

  1. OS-level Opt-out - managed by Opt out of Ads Personalization setting on device (preferred approach).
  2. User Choice - Direct call to SDK. Can be used without Google Play Services.

Special Note Regarding Apps in the Kids Category

If you are building an app that will be listed in the Kids Category:

  1. Ensure that you are using the NoID version of the Nielsen SDK Framework.
  2. Immediately following the initialization of the Nielsen SDK ensure you call the userOptOut API with Opt out selection:
appSdk.userOptOut("nielsenappsdk://1");  // User opt-out

OS-level Opt-out

OS-level Opt-out method available on Nielsen Android.

The Nielsen SDK automatically leverages the Android's Opt out of Ads Personalization setting. The user is opted out of demographic measurement if the OS-level "Opt out of Ads Personalization" setting is enabled. As a publisher, you cannot override this setting.

Get the latest Nielsen opt-out URL

Webview Example

The below code is an AndroidX example of displaying the Nielsen Privacy page to the user.

public class OptOutActivity extends AppCompatActivity implements IAppNotifier {

    WebView webView;
    AppSdk appSdk;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_optout);
        webView = (WebView) findViewById(R.id.webView);

        webView.getSettings().setJavaScriptEnabled(true);

        webView.setWebViewClient(new WebViewClient() {
            @SuppressWarnings("deprecation")
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(OptOutActivity.this, description, Toast.LENGTH_SHORT).show();
            }
            @TargetApi(android.os.Build.VERSION_CODES.M)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
                // Redirect to deprecated method, so you can use it in all SDK versions
                onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
            }
        });

        NielsenInit nielsenInit = new NielsenInit();       // Initializing the NielsenSDK
        appSdk = nielsenInit.initAppSdk(getApplicationContext(), this);    //Create Instance
        String url = appSdk.userOptOutURLString();   // Request Optout URL from NielsenSDK
        webView.loadUrl(url);                         //Display to the user in a Webview
    }


User Choice

The User Choice method is only necessary when the host application does not leverage Google Play Services.

Nielsen Android SDK 5.1.1.18 and above will check for OS-level opt-out first, if available. The user will be opted out if indicated at the OS-level OR the App-level.

The legacy opt-out method works as follows:

  • Get the current Nielsen opt-out URL via userOptOutURLString()
  • Display a WebView element whose loadUrl is set to the value obtained from userOptOutURLString()
  • Detect if the WebView URL changes to a special URL that indicates Opt-in, or Opt-out and close the WebView
    • Opt-out if the WebView URL = nielsenappsdk://1
    • Opt-in if the WebView URL = nielsenappsdk://0
  • Pass the detected URL to the userOptOut() function
    • Example:
      appSdk.userOptOut("nielsenappsdk://1");  // User opt-out
      

Legacy Opt Out example code

private class MonitorWebView extends WebViewClient
{
  private static final String NIELSEN_URL_OPT_OUT = "nielsenappsdk://1";
  private static final String NIELSEN_URL_OPT_IN = "nielsenappsdk://0";
 
  @Override
  public boolean shouldOverrideUrlLoading(WebView view, String url)
  {
    if (NIELSEN_URL_OPT_OUT.equals(url)
      || NIELSEN_URL_OPT_IN.equals(url))
    {
      // Get AppSdk instance from the host
      AppSdk appSdk = HostApp.getAppSdk();
      // Send the URL to the AppSdk instance
      appSdk.userOptOut(url);
      return true;
    }
    return false;
  }
}

Retrieve current Opt-Out preference

Whether the user is opted out viaOS-level Opt-out or via App-level Opt-out, the current Opt-Out status as detected by the SDK is available via the getOptOutStatus() property in the Nielsen Android SDK API,


Required Privacy Links

Users must either have access to the "About Nielsen Measurement" page, or have similar text available within the native app. Include "About Nielsen Measurement" and "Your Choices" link in the Privacy Policy / EULA or as a button near the link to the app's Privacy Policy.

In addition, the following text must be included in your app store description.

"Si prega di notare che questa app include il software di misurazione proprietario di Nielsen che contribuisce alla ricerca di mercato. Per ulteriori informazioni, si prega di consultare il seguente link https://www.nielsen.com/it/it/legal/privacy-statement/digital-measurement/"

Going Live

Following Nielsen testing, you will need to:

  1. Disable Debug Logging: Disable logging by deleting {nol_devDebug: 'DEBUG'} from initialization call.
  2. Notify Nielsen: Once you are ready to go live, let us know so we can enable you for reporting. We will not be able to collect or report data prior to receiving notification from you.

Sample Applications