Simplified SDK API-Android

From Engineering Client Portal

The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Engineering Portal breadcrumbArrow.png Digital breadcrumbArrow.png DCR & DTVR breadcrumbArrow.png Simplified SDK APIbreadcrumbArrow.png Simplified SDK API-Android

Android1.jpg

Android Studio Java Code Example

Select the below link to download the sample files
Download Project Files

NielsenInit.java

// This is sample code of a very basic implementation of the Nielsen 'Simplified API'
// This code is for educational purposes only
//

import android.content.Context;

import com.nielsen.app.sdk.IAppNotifier;
import com.nielsen.app.sdk.NielsenEventTracker;

import org.json.JSONException;
import org.json.JSONObject;

public class NielsenInit {

    private NielsenEventTracker mEventTracker = null;

    public NielsenEventTracker initEventTracker(Context mContext, IAppNotifier appNotifier){

        try {

            //Initialising the NielsenEventTracker class by passing app information which returns the instance of NielsenEventTracker.

            JSONObject appInformation = new JSONObject()

                    .put("appid", "PDA7D5EE6-B1B8-4123-9277-2A788BC6XXX")
                    .put("appversion", "1.0")
                    .put("appname", "Android Test app")
                    .put("sfcode", "dcr")
                    .put("ccode", "123")
                    .put("dma","456")
                    .put("uoo","0")
                    .put("nol_devDebug", "INFO")
                    .put("containerId", "0");

            mEventTracker = new NielsenEventTracker(mContext, appInformation, appNotifier);

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return mEventTracker;
    }
}

SDKMethods.java

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created on 07/02/18.
 */

public class SDKMethods {

    public String url = "";
    JSONObject content = null;
  //Loading content Data
    public JSONObject loadContentData(){

        url = "http://www.nielseninternet.com/NielsenConsumer/prog_index.m3u8";

        JSONObject data = null;
        try {
            JSONObject content = new JSONObject()
                    .put( "assetName","ChromeCast1")
                    .put( "assetid","C77664")
                    .put( "length","3600")
                    .put( "program","MyProgram")
                    .put( "segB","CustomSegmentValueB")
                    .put( "segC","segmentC")
                    .put( "title","S2,E3")
                    .put( "type","content")
                    .put( "section","cloudApi_app")
                    .put( "airdate","20180120 10:00:00")
                    .put( "isfullepisode","y")
                    .put( "adloadtype","2")
                    .put( "channelName","My Channel 1")
                    .put( "pipMode","false");

            //Ad data,static data should be empty in content video dictionary
            JSONObject metaData = new JSONObject()
                    .put("content", content)
                    .put("ad", new JSONObject())
                    .put("static", new JSONObject());

            data = new JSONObject()
                    .put("metadata", metaData)
                    .put("event", "playhead")
                    .put("type", "content")
                    .put("playheadPosition", "0");



        } catch (JSONException e) {
                e.printStackTrace();
        }

        return data;

    }

MainActivity.java

package com.simplifiedapiapp.activities;

import android.app.ProgressDialog;
import android.media.MediaPlayer;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;

import com.simplifiedapiapp.utils.Constants;
import com.simplifiedapiapp.models.NielsenInit;
import com.simplifiedapiapp.R;
import com.simplifiedapiapp.models.SDKMethods;
import com.nielsen.app.sdk.IAppNotifier;
import com.nielsen.app.sdk.NielsenEventTracker;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

public class MainActivity extends AppCompatActivity implements IAppNotifier, SurfaceHolder.Callback, MediaPlayer.OnPreparedListener, View.OnClickListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener {

    public static final String TAG = MainActivity.class.getSimpleName();

    private SurfaceView mSurfaceView;
    private SeekBar seek;
    Button btnPlay;

    NielsenEventTracker eventTracker;
    private int videoType, totalVideos;
    private int totalVideosPlayed = 0;
    private boolean isVideoStarted = false, isPaused = false;
    JSONObject data = null;

    private MediaPlayer mMediaPlayer;
    private SurfaceHolder mSurfaceHolder;

    SDKMethods sdkMethods;

    private ProgressDialog dialog;
    private Handler playheadHandler;
    private Runnable playheadRunnable;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //In SDKMethods class we wrote methods which creates content,Ad objects
        sdkMethods = new SDKMethods();

        getIntents();
        initUI();

        //In NielsenInit class we are initialising the NielsenEventTracker.
        //Getting the instance of NielsenEventTracker
        NielsenInit nielsenInit = new NielsenInit();

        //3rd parameter "this" referes to IAppNotifier interface which is needed to initialise NielsenEventTracker
        eventTracker = nielsenInit.initEventTracker(getApplicationContext(), this);
    }

    @Override
    protected void onResume() {
        super.onResume();

        //loading static data
        JSONObject staticObj = sdkMethods.loadStaticData();

        //sending static data to SDK.
        eventTracker.trackEvent(staticObj);
    }

    private void initUI() {

        seek = (SeekBar) findViewById(R.id.seek);
        btnPlay = (Button) findViewById(R.id.btnPlay);
        btnPlay.setOnClickListener(this);
    }

    private void getIntents() {

        videoType = getIntent().getIntExtra(Constants.INTENT_VIDEO_TYPE, 0);
        totalVideos = getIntent().getIntExtra(Constants.INTENT_TOTAL_VIDEOS, 0);


        if (videoType == Constants.onlyContent) {

            //loading video content data
            data = sdkMethods.loadContentData();
        } else {

            //loading Ad data
            data = sdkMethods.loadPreRollAdData();
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {

        Log.v(TAG, "surfaceCreated Called");

        if (isPaused) {
            //Once video is resumed after pause, setting surfaceholder to player.
            if (mMediaPlayer != null) {

                mSurfaceHolder = mSurfaceView.getHolder();
                mMediaPlayer.setDisplay(mSurfaceHolder);
            }

        } else {

            //This will execute for first time.
            setUpPlayer();
            mMediaPlayer.setOnCompletionListener(this);
            mMediaPlayer.setOnErrorListener(this);
        }
    }

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        try {

            playheadHandler.removeCallbacks(playheadRunnable);

            ///As 1 video completed playing, incrementing the variable value.
            totalVideosPlayed++;

            if (videoType == Constants.onlyContent || totalVideosPlayed == totalVideos) {

                //on content video complete, updating event as "complete" in object
                data.put("event", "complete");
            } else {
                //on Ad complete, updating event as "adStop" in object
                data.put("event", "adStop");
            }

            //sending the object to SDK.
            eventTracker.trackEvent(data);

            releaseMediaPlayer();

            checkVideosToBePlayed();

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void checkVideosToBePlayed(){

        //Checking if total videos played or not.
        if (totalVideosPlayed != totalVideos) {

            data = new JSONObject();

            //Checking if videoType is contentWithOneAd, then after completion of Ad, will play the content video.
            if (videoType == Constants.contentWithOneAd) {

                //loading video content data
                data = sdkMethods.loadContentData();

            } else if (videoType == Constants.contentWithTwoAds) {
                if (totalVideosPlayed == 1) {

                    //loading 2nd Ad data
                    data = sdkMethods.loadMidRollAdData();
                } else {

                    //loading video content data
                    data = sdkMethods.loadContentData();
                }
            }

            showProgressDialog();

            setUpPlayer();

            mMediaPlayer.setOnCompletionListener(this);
            mMediaPlayer.setOnErrorListener(this);

        }
    }

    @Override
    public boolean onError(MediaPlayer mediaPlayer, int i, int li) {
        Log.e(TAG, "Player error codes:" + i + ", " + li);
        return false;
    }

    //creating player
    private void setUpPlayer() {
        try {

            mMediaPlayer = new MediaPlayer();
            mMediaPlayer.setDisplay(mSurfaceHolder);
            mMediaPlayer.setDataSource(sdkMethods.url);
            mMediaPlayer.setOnPreparedListener(MainActivity.this);
            mMediaPlayer.prepareAsync();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        Log.v(TAG, "surfaceChanged Called");
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        Log.v(TAG, "surfaceDestroyed Called");
    }

    @Override
    public void onPrepared(MediaPlayer mp) {

        if (dialog.isShowing()) {
            dialog.dismiss();
        }

        seek.setMax(convertTotime(mMediaPlayer.getDuration()));
        isVideoStarted = true;

        updateSeekbarAndPlayhead();
        mMediaPlayer.start();

    }

    @Override
    protected void onPause() {
        super.onPause();

        setPauseAction();
    }

    private void setPauseAction() {
        try {
            if (mMediaPlayer != null) {

                isVideoStarted = false;
                isPaused = true;
                mMediaPlayer.pause();


                //on video pause, updating event as pause in object
                data.put("event", "pause");

                //sending the object to SDK with "pause" event.
                eventTracker.trackEvent(data);

                btnPlay.setText(getString(R.string.play));

            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseMediaPlayer();
    }

    private void releaseMediaPlayer() {
        if (mMediaPlayer != null) {
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnPlay:
                try {
                    //If video is not yet played, then it will play else it will pause the video
                    if (!isVideoStarted) {

                        btnPlay.setText(getString(R.string.pause));

                        if (isPaused) {

                            isVideoStarted = true;
                            isPaused = false;

                            //Once the video is resumed after pause, setting event as "playhead".
                            data.put("event", "playhead");
                            mMediaPlayer.start();

                        } else {

                            mSurfaceView = (SurfaceView) findViewById(R.id.surface_view);
                            mSurfaceView.setVisibility(View.VISIBLE);

                            showProgressDialog();

                            mSurfaceHolder = mSurfaceView.getHolder();
                            mSurfaceHolder.addCallback(MainActivity.this);

                        }

                    } else {
                        setPauseAction();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }

    }

    //Updates seekbar
    private void updateSeekbarAndPlayhead() {
        try {
            //to update playhead, setting the event as "playhead".
            data.put("event", "playhead");
            playheadHandler = new Handler();


            //Make sure you update Seekbar on UI thread
            MainActivity.this.runOnUiThread(playheadRunnable = new Runnable() {

                @Override
                public void run() {
                    if (mMediaPlayer != null) {
                        int mCurrentPosition = mMediaPlayer.getCurrentPosition() / 1000;
                        seek.setProgress(mCurrentPosition);
                        try {
                            if (!isPaused && mMediaPlayer.isPlaying()) {

                                //updating playHead position in Object each second.
                                data.put("playheadPosition", String.valueOf(mCurrentPosition));

                                //Sending data object to SDK with updated playHead position.
                                eventTracker.trackEvent(data);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                    playheadHandler.postDelayed(this, 1000);
                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private int convertTotime(long milliSec) {

        int minutes = (int) (milliSec / 1000);
        return minutes;
    }

    private void showProgressDialog() {

        runOnUiThread(new Runnable() {
            public void run() {
                dialog = new ProgressDialog(MainActivity.this);
                dialog.setCancelable(false);
                dialog.setMessage(getString(R.string.loading));
                dialog.show();
            }
        });
    }


    @Override
    public void onAppSdkEvent(long l, int i, String s) {

        //IAppNotifier method
    }
}