# InStreamAd

**package com.intowow\.sdk**

**public class InStreamAd**

## Characteristics

* **There are three types of in-stream video ads: pre-roll, mid-roll and post-roll.**
  * **Pre-roll ads**

    Pre-roll ads are displayed before the content video. These ads are played only once when user starts the playback of content video.
  * **Post-roll ads**

    Post-roll ads are displayed after the content video has finished playing. These ads are played only once when the content video has finished playing.
  * **Mid-roll ads**

    Mid-roll ads are shown in the middle of content video at breakpoints. Mid-roll ads may be shown multiple times during single video. Mid-roll ad can be served depends on cue points.

    * Cue points at which to show ads may be defined in several ways in Mid-roll ads. You can display ads by **Every n seconds**, **Fixed time** or **Fixed percentage**.
    * Ad break at each cue point can choose the following rule to play video ad in the Ad break, **Single, Fixed time** or **Multi Ad.**

## Integration

#### Declare InStreamAd

* Create a InStreamAd instance and keep its reference.

```java
import com.intowow.sdk.InStreamAd;

private final static String PLACEMENT = "Obtain from your Intowow account manager";
private InStreamAd mInStreamAd = null;
```

#### Initialize InStreamAd

```java
// [NOTE]
// It is recommended to initialize as early as possible.
// You can send more information to custom event if necessary through requestInfo. (optional)

Map<String, Object> adProps = new HashMap<>();
adProps.put(AdProperty.HIDE_COUNTDOWN, false);
adProps.put(AdProperty.HIDE_SPEAKER, false);
adProps.put(AdProperty.HIDE_AD_ICON, false);
adProps.put(AdProperty.SILENT_START, false);
adProps.put(AdProperty.HIDE_NON_SKIPPABLE_BUTTON, false);
adProps.put(AdProperty.HIDE_AD_COUNT_VIEW, false);

final RequestInfo requestInfo = new RequestInfo();
JSONObject localExtra = new JSONObject();
try {
    localExtra.put("more_info", "Your extra information");
} catch (JSONException e) {
    e.printStackTrace();
}
requestInfo.setLocalExtra(localExtra);

mInStreamAd = new InStreamAd(this, PLACEMENT, adProps, mContainer, requestInfo);
// ***DEPRECATED*** //
// mInStreamAd = new InStreamAd(this, PLACEMENT, adProps, mContainer);
// **************** //
```

#### Implement InStreamAdListener to handle InStreamAd Event

```java
mInStreamAd.setAdListener(new InStreamAd.InStreamAdListener() {

    @Override
    public void onAdError(InStreamAd ad, AdError error) {
        // [NOTE]
        // Callback if fail to load an InStream ad from Intowow SDK
        //
    }

    @Override
    public void onVideoStart(InStreamAd ad) {
    }

    @Override
    public void onVideoEnd(InStreamAd ad) {
    }

    @Override
    public void onAdClicked(InStreamAd ad) {
    }

    @Override
    public void onAdMute(InStreamAd ad) {
    }

    @Override
    public void onAdUnmute(InStreamAd ad) {
    }

    @Override
    public void onAdImpression(InStreamAd ad) {
    }

    @Override
    public void onProgress(InStreamAd ad, long totalDuration, long currentPosition) {
        // [NOTE]
        // onProgress is best for monitoring
        // e.g.
        //ad.getAdBreakRemainTime();
        //ad.getAdRemainTime();
        //ad.getCurrentAdNum();
        //ad.getTotalAdNum();
        //
    }

    @Override
    public void onRequestContentPause(InStreamAd ad, int adBreakType,
                                                  long cuePointTime) {
        // [NOTE]
        // After onRequestContentPause, ad is ready
        // and can be played after video player is paused.
        // 
        // [Pre-roll]
        // When the ad arrives late, please aware that Preroll ad
        // will callback here after the content has started.
        // You need to handle this situation when cuePointTime = 0.
        //
        if(yourMediaPlayer != null && yourMediaPlayer.isPlaying()) {
            yourMediaPlayer.pause();
        }
        if (mInStreamAd != null) {
            mInStreamAd.play();
        }
    }

    @Override
    public void onRequestContentResume(InStreamAd ad, long adRemainTime) {
        // [NOTE]
        // Two scenario to trigger inStreamADRequestContentResume: 
        // (1) Video ad is finished (adRemainTime = 0)
        //    --> Please stop inStreamAD and resume Video Player
        // (2) Time requirement of ad break has been met (adRemainTime > 0)
        //    --> Resume Video Player or keep playing ad is up to you. 
        //        If you chose to complete playing video ad, inStreamADRequestContentResume
        //        will be called again once ad is finished(scenario (1)).
        //
        //
        // [Best Practice]
        // onRequestContentResume is best for resume playing video
        // content if InStream ad finished playing.
        //
        if (mInStreamAd != null && adRemainTime == 0) {
            mInStreamAd.stop();
        }
        yourMediaPlayer.start();
    }

    @Override
    public void onCuePointsReady(InStreamAd ad) {
        // [NOTE]
        // getCuePoint shall be called after onCuePointsReady
        // e.g.
        // ad.getCuePoints();
        //
    }
);
```

#### Request InStreamAd

* `startAutoRequestAd` **must be** called **after** InStreamAd instance is initialized
* `startAutoRequestAd` **shall be** called **before** video content is played, otherwise ad breaks in the beginning of the video, pre-roll ad especially, will be wasted
* Please called `startAutoRequestAd` only one time.&#x20;

```java
mInStreamAd.startAutoRequestAD();
```

#### Implement CEContentProgressProvider to update Video Content Status

* `isContentPlayerReady`, `getContentCurrentPosition` and `getContentTotalDuration` **must be** implemented otherwise InStream ad will not be served
* **Please read this carefully:** During the time user is seeking the video, APP should always return the progress time that user start seeking instead of the current time that user has sought to. Once user stop seeking, please return the progress time that user stopped at.

  ![](https://1252529651-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGU_q6Cp7glylaa3ogy%2F-LGU_uDXyKLpZsKhgGZa%2F-LGUa-BxfR9Z2TbhwWCO%2Fseeking-intowow.png?generation=1530612180177064\&alt=media)

```java
mInStreamAd.setContentProgressProvider(new InStreamAd.CEContentProgressProvider() {

    @Override
    public long getContentCurrentPosition() {
        if (yourMediaPlayer == null) {
            return 0;
        } else if (isSeeking) {
            return mLastPosition;
        }
        return yourMediaPlayer.getCurrentPosition();
    }

    @Override
    public long getContentTotalDuration() {
        if (yourMediaPlayer == null) {
            return 0;
        }

        return yourMediaPlayer.getDuration();
    }

    @Override
    public boolean isContentPlayerReady() {
        return yourMediaPlayerReady;
    }
});
```

#### Release InStreamAd

* InStream ad shall at least be released along with the life cycle of video content

```java
@Override
protected void onDestroy() {
    if (mInStreamAd != null) {
        mInStreamAd.destroy();
        mInStreamAd = null;
    }

    if (yourMediaPlayer != null) {
        yourMediaPlayer.release();
        yourMediaPlayer = null;
    }
    super.onDestroy();
}
```

### Advance Integration

#### Note

* You could use [setAdSize(CEAdSize adSize)](#setAdSize) to instruct SDK to set an expected width and height of the ad, and SDK will rescale the ad automatically and keeps the aspect ratio.
* If you want to resize the ad, please use [resize(CEAdSize adSize)](#resize).

#### AdProperty

* You could use `AdProperty` to configure your ad if necessary:

```java
Map<String, Object> adProps = new HashMap<String, Object>();
adProps.put(AdProperty.HIDE_COUNTDOWN, trueOrFalse);
adProps.put(AdProperty.HIDE_SPEAKER, trueOrFalse);
adProps.put(AdProperty.HIDE_AD_ICON, trueOrFalse);
adProps.put(AdProperty.SILENT_START, trueOrFalse);
adProps.put(AdProperty.HIDE_NON_SKIPPABLE_BUTTON, trueOrFalse);
adProps.put(AdProperty.HIDE_AD_COUNT_VIEW, trueOrFalse);

InstreamAd mInStreamAd = new InstreamAd(context, placement, adProps, container);
```

![](https://1252529651-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGU_q6Cp7glylaa3ogy%2F-LGU_uDXyKLpZsKhgGZa%2F-LGUa-C5sVLJ-01kmy-V%2Fproperty-instream.png?generation=1530612180133245\&alt=media)

(A)`AdProperty.HIDE_SPEAKER`: if need to hide the speaker on top left corner, the default value is false.

(B) `AdProperty.HIDE_AD_COUNT_VIEW`: if need to hide the ad count view on bottom left corner, the default value is false.

(C) `AdProperty.HIDE_AD_ICON`: if need to hide the ad icon on top right corner, the default value is false.

(D) `AdProperty.HIDE_COUNTDOWN`: if need to hide the count down timer on top right corner, the default value is false.

(E) `AdProperty.HIDE_NON_SKIPPABLE_BUTTON`: if need to hide skippable button on bottom right corner, the default value is false.

(F) `AdProperty.SILENT_START`: auto silent play, the default value is true.

#### Customized Skip Button

1. Put the AdProperty to `HIDE_NON_SKIPPLE_BUTTON` or the customized skip button will overlap with default one.
2. Please pass any views that overlap ad view by [`registerFriendlyObstruction`](#registerFriendlyObstruction) for the completeness of viewability tracking.
3. Customized view must be passed by `registerFriendlyObstruction` if it is on top of and overlap InStream ad.
4. **\[Recommended]** Mechanism to show and hide customized Skip button need to be handled by APP. Default Skip button from Intowow SDk needs no effort from APP and is recommended.

```java
// Sample for Setting up Customized Skip button
mCustomNonSkipableButton = new CustomNonSkipableButton(InStreamAdActivity.this);

// [Notice] remember to register custom non-skippable button.
mInStreamAd.registerViewForDismiss(mCustomNonSkipableButton);
List<View> obstructionViews = new ArrayList<View>();
obstructionViews.add(mCustomNonSkipableButton);

// [Notice] remember to register custom non-skippable button to obstruction.
mInStreamAd.registerFriendlyObstruction(obstructionViews);
```

## API Reference

| Public constructors                                                                                                                                                              |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| <p><a href="#InStreamAd">InStreamAd(Context context, String placement, Map adProps, ViewGroup adContainer, RequestInfo requestInfo)</a> <br> Instantiates a new InStream ad.</p> |
| <p><a href="#InStreamAdDEPRECATED">InStreamAd(Context context, String placement, Map adProps, ViewGroup adContainer)</a> <br> (Deprecated)Instantiates a new InStream ad.</p>    |

| Public methods |                                                                                                                                                                                                                                                                                                                                                                |
| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| void           | <p><a href="#registerViewForDismiss">registerViewForDismiss(View view)</a> <br> Register view as Skip button.</p>                                                                                                                                                                                                                                              |
| void           | <p><a href="#registerFriendlyObstruction">registerFriendlyObstruction(List views)</a> <br> Please pass any views that overlap ad view so that viewability tracking can be completed.</p>                                                                                                                                                                       |
| void           | <p><a href="#setAdListener">setAdListener(final InStreamAdListener listener)</a> <br> Set ad listener to InStream ad.</p>                                                                                                                                                                                                                                      |
| void           | <p><a href="#setContentProgressProvider">setContentProgressProvider(CEContentProgressProvider contentProgressProvider)</a> <br> Set contentProgressProvider to InStream ad.</p>                                                                                                                                                                                |
| void           | <p><a href="#setAdSize">setAdSize(CEAdSize adSize)</a> <br> Set adSize to InStream ad.</p>                                                                                                                                                                                                                                                                     |
| void           | <p><a href="#startAutoRequestAd">startAutoRequestAd()</a> <br> Request in-stream ads automatically.<br> It  shall only be called once after InStreamAd is intialized.</p>                                                                                                                                                                                      |
| void           | <p><a href="#contentComplete">contentComplete()</a> <br> Notification of the end of video content.<br><strong>It is critical to ensure Post-roll ad being served. If it is called in the middle of video content and there is ad to be served, post-roll ad will be served.</strong></p>                                                                       |
| void           | <p><a href="#play">play()</a> <br> Play InStream ad.</p>                                                                                                                                                                                                                                                                                                       |
| void           | <p><a href="#stop">stop()</a> <br> Stop InStream ad.<br><strong>Once certain  InStream video ad is stopped, it cannot resumes playing.</strong></p>                                                                                                                                                                                                            |
| void           | <p><a href="#destroy">destroy()</a> <br> Release InStream ad.<br>InStream Ad shall at least  be released along with video player.</p>                                                                                                                                                                                                                          |
| `List< Long >` | <p><a href="#getCuePoints">getCuePoints()</a> <br> Return a list of cue points in Long representing milli-second.<br>Return <code>null</code> if total duration of content video is not available.</p>                                                                                                                                                         |
| int            | <p><a href="#getCurrentAdNum">getCurrentAdNum()</a> <br> Return the index(Start from 1) of InStream ad that is playing out of the number of ad should be served in current ad break.<br><strong>It should be called during ad break, otherwise it will return</strong> <code>CE\_CURRENT\_AD\_NUM\_INVALID</code><strong>.</strong></p>                        |
| int            | <p><a href="#getTotalAdNum">getTotalAdNum()</a> <br> Return the total number of InStream that is expected to be played within current ad break.<br><strong>If it is not called in ad break or it is called in ad break but the total number of ad is not predictable,</strong> <code>CE\_TOTAL\_AD\_NUM\_INVALID</code> <strong>will be returned.</strong></p> |
| long           | <p><a href="#getAdBreakRemainTime">getAdBreakRemainTime()</a> <br> Return the time left for current ad break.<br><strong>If it is not called in ad break or it is called in ad break but the remaining time of ad break cannot be calculated,</strong> <code>CE\_AD\_BREAK\_REMAIN\_TIME\_INVALID</code> <strong>will be returned.</strong></p>                |
| long           | <p><a href="#getAdRemainTime">getAdRemainTime()</a> <br> Return the time left for current playing InStream ad.<br><strong>It should be called during ad break, otherwise it will return</strong> <code>CE\_AD\_REMAIN\_TIME\_INVALID</code><strong>.</strong></p>                                                                                              |
| JSONObject     | <p><a href="#getExtra">getExtra()</a> <br> Return the extra info that is set in custom event. Receiving null is expected if no object is set.</p>                                                                                                                                                                                                              |

## Public Constructors

### InStreamAd <a href="#instreamad" id="instreamad"></a>

```java
InStreamAd(Context context, String placement, Map<String, Object> adProps, ViewGroup adContainer, RequestInfo requestInfo)
```

Instantiates a new InStream ad.

| Parameters  |                                                                                                                                   |
| ----------- | --------------------------------------------------------------------------------------------------------------------------------- |
| context     | Context                                                                                                                           |
| placement   | String: A specific group of ad units on which an advertiser can choose to place their ads using placement targeting               |
| adProps     | Map: the ad property                                                                                                              |
| adContainer | ViewGroup: ViewGroup that Ad belongs to                                                                                           |
| RequestInfo | RequestInfo: Extra info for requesting AD. If no additional info is needed, APP can pass either null or the requestInfo instance. |

### InStreamAd(Deprecated) <a href="#instreamaddeprecated" id="instreamaddeprecated"></a>

```java
InStreamAd(Context context, String placement, Map<String, Object> adProps, ViewGroup adContainer)
```

Instantiates a new InStream ad.

| Parameters  |                                                                                                                     |
| ----------- | ------------------------------------------------------------------------------------------------------------------- |
| context     | Context                                                                                                             |
| placement   | String: A specific group of ad units on which an advertiser can choose to place their ads using placement targeting |
| adProps     | Map: the ad property                                                                                                |
| adContainer | ViewGroup: ViewGroup that Ad belongs to                                                                             |

## Public Methods

### registerViewForDismiss <a href="#registerviewfordismiss" id="registerviewfordismiss"></a>

```
void registerViewForDismiss(View view)
```

Register view as Skip button.

| Parameters |                                                 |
| ---------- | ----------------------------------------------- |
| view       | View: The View to be registered for skip event. |

### registerFriendlyObstruction <a href="#registerfriendlyobstruction" id="registerfriendlyobstruction"></a>

```
void registerFriendlyObstruction(List<View> views)
```

Please pass any views that overlap ad view so that viewability tracking can be completed.

| Parameters |                                                              |
| ---------- | ------------------------------------------------------------ |
| views      | List: List of View storing all views overlapping InStream ad |

### setAdListener <a href="#setadlistener" id="setadlistener"></a>

```
void setAdListener(final InStreamAdListener listener)
```

Set ad listener to InStream ad.

| Parameters |                    |
| ---------- | ------------------ |
| listener   | InStreamAdListener |

### setContentProgressProvider <a href="#setcontentprogressprovider" id="setcontentprogressprovider"></a>

```
void setContentProgressProvider(CEContentProgressProvider contentProgressProvider)
```

Set contentProgressProvider to InStream ad.

| Parameters              |                           |
| ----------------------- | ------------------------- |
| contentProgressProvider | CEContentProgressProvider |

### setAdSize <a href="#setadsize" id="setadsize"></a>

```
void setAdSize(CEAdSize adSize)
```

Set adsize to InStream ad.

| Parameters |          |
| ---------- | -------- |
| adSize     | CEAdSize |

### startAutoRequestAd <a href="#startautorequestad" id="startautorequestad"></a>

```
void startAutoRequestAd()
```

Request in-stream ads automatically. It shall only be called once after InStreamAd is intialized.

### contentComplete <a href="#contentcomplete" id="contentcomplete"></a>

```
void contentComplete()
```

Notification of the end of video content. **It is critical to ensure Post-roll ad being served. If it is called in the middle of video content and there is ad to be served, post-roll ad will be served.**

### play <a href="#play" id="play"></a>

```
void play()
```

Play InStream ad.

### stop <a href="#stop" id="stop"></a>

```
void stop()
```

Stop InStream ad. **Once certain InStream video ad is stopped, it cannot resume playing.**

### destroy <a href="#destroy" id="destroy"></a>

```
void destroy()
```

Release InStream ad. InStream Ad shall at least be released along with the life cycle of video content.

### getCuePoints <a href="#getcuepoints" id="getcuepoints"></a>

```
List<Long> getCuePoints()
```

Return a list of cue points in Long representing milli-second. Return `null` if total duration of content video is not available.

| Returns        |                                                            |
| -------------- | ---------------------------------------------------------- |
| `List< Long >` | List with all cue points in Long representing milli-second |

### getCurrentADNum <a href="#getcurrentadnum" id="getcurrentadnum"></a>

```
int getCurrentADNum()
```

Return the index(Start from 1) of InStream ad that is playing out of the number of ad should be served in current ad break. **It should be called during ad break, otherwise it will return** `CE_CURRENT_AD_NUM_INVALID`**.**

| Returns |                                                              |
| ------- | ------------------------------------------------------------ |
| int     | The index of InStream ad that is playing in current ad break |

### getTotalAdNum <a href="#gettotaladnum" id="gettotaladnum"></a>

```
int getTotalAdNum()
```

Return the total number of InStream ad that is expected to be played within current ad break. **If it is not called in ad break or it is called in ad break but the total number of ad is not predictable,** `CE_TOTAL_AD_NUM_INVALID` **will be returned.**

| Returns |                                                                               |
| ------- | ----------------------------------------------------------------------------- |
| int     | Total number of InStream ad that is expected to be played in current ad break |

### getAdBreakRemainTime <a href="#getadbreakremaintime" id="getadbreakremaintime"></a>

```
long getAdBreakRemainTime()
```

Return the time left for current ad break. **If it is not called in ad break or it is called in ad break but the remaining time of ad break cannot be calculated,** `CE_AD_BREAK_REMAIN_TIME_INVALID` **will be returned.**

| Returns |                                    |
| ------- | ---------------------------------- |
| long    | The time left for current ad break |

### getAdRemainTime <a href="#getadremaintime" id="getadremaintime"></a>

```
long getAdRemainTime()
```

Return the time left for current playing InStream ad. **It should be called during ad break, otherwise it will return** `CE_AD_REMAIN_TIME_INVALID`**.**

| Returns |                                               |
| ------- | --------------------------------------------- |
| long    | The time left for current playing InStream ad |

### getExtra <a href="#getextra" id="getextra"></a>

```
JSONObject getExtra()
```

Return the extra info that is set in custom event. Receiving null is expected if no object is set.

| Returns    |                                             |
| ---------- | ------------------------------------------- |
| JSONObject | The extra info that is set in custom event. |
