TubiVPAID.java
Overview
`TubiVPAID` is a helper class designed to enable playback of **VPAID (Video Player Ad-Serving Interface Definition)** ads within an Android native application by embedding a **WebView**. Since VPAID ads are primarily built for mobile web environments and rely heavily on JavaScript interaction, this class manages a WebView configured to load a VPAID-compliant ad player hosted remotely (e.g., on tubitv.com). It acts as a bridge between the native Android media playback finite state machine (`FsmPlayer`) and the JavaScript environment running the VPAID ad, facilitating two-way communication and lifecycle management.
The class implements the [VpaidClient](/projects/288/68374) interface and manages:
WebView setup and configuration for VPAID playback
JavaScript interface methods to receive notifications from the VPAID ad player (e.g., ad completion, errors)
Delivery of VAST XML ad data to the JavaScript player
Handling of WebView errors and permission requests
Posting events safely to the UI thread handler to interact with the FSM player
This design ensures seamless integration of interactive VPAID ads within the native media playback workflow controlled by the FSM.
Detailed Explanation
Class: TubiVPAID
Implements the [VpaidClient](/projects/288/68374) interface, encapsulating all logic necessary to play VPAID ads inside a WebView and communicate with the FSM player.
Properties
Property | Type | Description |
|---|---|---|
`TAG` | `String` | Log tag for debugging and error messages |
`mVPAIDWebView` | `WebView` | The WebView instance hosting the VPAID player |
`mHandler` | `Handler` | UI thread handler to post runnable actions |
`vastXml` | `String` | VAST XML ad data string fetched from `Vastxml` |
`fsmPlayer` | `FsmAdController` | Reference to the FSM player managing ad states |
Constructor
public TubiVPAID(@NonNull WebView webView, @NonNull Handler uiHandler, @NonNull FsmPlayer fsmPlayer)
Parameters:
webView: TheWebViewinstance to be used for playing VPAID ads.uiHandler: AHandlerassociated with the UI thread for posting UI-related tasks.fsmPlayer: The FSM player instance managing ad playback state transitions.
Behavior:
Initializes internal references to the provided WebView, handler, and FSM player.Usage Example:
WebView vpaidWebView = findViewById(R.id.vpaidWebView);
Handler uiHandler = new Handler(Looper.getMainLooper());
FsmPlayer fsmPlayer = ...; // Obtain FSM player instance
TubiVPAID vpaidClient = new TubiVPAID(vpaidWebView, uiHandler, fsmPlayer);
Method: init
@SuppressLint("SetJavaScriptEnabled")
@TargetApi(21)
public void init(@Nullable MediaModel mediaModel)
Parameters:
mediaModel: Optional media model representing the ad media to be played (currently unused in implementation).
Returns:
voidDescription:
Initializes and configures the WebView for VPAID playback by:Loading an empty URL to reset the WebView
Clearing browsing history
Setting custom
WebViewClientandWebChromeClientto manage URL loading, errors, and permissionsEnabling JavaScript and disabling user gesture requirements for media playback
Allowing mixed content (HTTP and HTTPS)
Enabling WebView debugging in debug builds
Usage Example:
vpaidClient.init(null);
JavaScript Interface Methods
These methods are exposed to JavaScript inside the WebView via the `@JavascriptInterface` annotation, allowing the VPAID ad player to communicate with the native app.
notifyVideoEnd
@JavascriptInterface
public void notifyVideoEnd()
Parameters: None
Returns: None
Description:
Called by the JavaScript VPAID player when the ad finishes playing. It posts a runnable on the UI thread that instructs the FSM player to remove the played ad and transition to the next playback state.Usage Example (called internally by JS):
window.TubiNativeJSInterface.notifyVideoEnd();
notifyAdError
@JavascriptInterface
public void notifyAdError(int code, String error)
Parameters:
code: Integer error code (e.g., HTTP error code or -1 if unavailable)error: Error message string describing the issue
Returns: None
Description:
Called by JavaScript code on encountering an error during ad playback. Logs the error and posts a runnable to the UI thread to advance the FSM player state, effectively skipping the failed ad.Usage Example (called internally by JS):
window.TubiNativeJSInterface.notifyAdError(404, "Ad creative not found");
getVastXml
@JavascriptInterface
public String getVastXml()
Parameters: None
Returns:
Stringcontaining the VAST XML ad dataDescription:
Provides the VAST XML ad description to the JavaScript VPAID player upon request.Usage Example (called internally by JS):
var vastXml = window.TubiNativeJSInterface.getVastXml();
Inner Classes
VPAidWebViewClient (extends WebViewClient)
Custom WebViewClient to handle URL loading and error handling specifically for the VPAID WebView.
Key Overrides:
shouldOverrideUrlLoading(WebView view, String url):
Forces all URL navigation to stay within the WebView by loading URLs inside it.onReceivedError(WebView view, int errorCode, String description, String failingUrl):
Handles error scenarios such as network failures. Logs errors and signals the FSM player to move on.onReceivedError(WebView view, WebResourceRequest request, WebResourceError error):
Overloaded method for API 23+ that delegates to the olderonReceivedError.
Behavior:
Prevents the WebView from crashing or leaving the app on errors and ensures the FSM can handle failures gracefully.
VPAIDWebChromeClient (extends WebChromeClient)
Custom WebChromeClient to manage video loading UI and permission requests.
Properties:
mVideoProgressView: Optional view shown while video is loading.
Key Overrides:
getVideoLoadingProgressView():
Returns the loading progress view if set.onPermissionRequest(PermissionRequest request):
Denies all permission requests from the WebView to prevent abuse or unauthorized access.
Usage:
Can be extended to support fullscreen playback or custom UI elements for video progress.
Important Implementation Details
Thread Safety:
All FSM player state changes and UI updates are posted to the UI thread viaHandlerto avoid thread conflicts.WebView Setup:
The WebView is carefully configured to allow mixed content, enable JavaScript, and disable the need for user gestures for media playback, complying with VPAID ad requirements.Error Handling:
Both JavaScript errors (notifyAdError) and WebView resource loading errors trigger FSM transitions to ensure the ad experience does not block playback indefinitely.JavaScript Interface Naming:
The JavaScript interface is added to the WebView under the name"TubiNativeJSInterface", which the VPAID JavaScript player uses to call native methods.VAST XML Source:
The VAST XML is retrieved from a helper classVastxml.getAdXmlBody()and provided to the JS player on demand.
Interaction with Other System Components
Finite State Machine (FSM) Player (
FsmPlayer):TubiVPAIDnotifies the FSM player when the VPAID ad finishes or errors out, prompting state transitions to resume content playback.Media Models (
MediaModel):
Although currently unused in theinit()method,MediaModelmay represent the ad to be played.UI Controller (
PlayerUIController):
Controls visibility of the WebView and ExoPlayer views during VPAID ad playback.VAST XML Provider (
Vastxml):
Supplies the VAST XML string used by the VPAID JavaScript player.WebView Activity (
WebviewActivity):
Hosts the WebView UI and initializes theTubiVPAIDclient.Dependency Injection:
TheTubiVPAIDclient is typically injected with the WebView, handler, and FSM player via Dagger or other DI frameworks to decouple components.
Usage Flow Summary
Initialization:
TheTubiVPAIDclient is instantiated with a WebView, UI thread handler, and FSM player.WebView Configuration:
init()configures the WebView and loads an empty URL to reset it.JavaScript Interface Setup:
The JavaScript interface (TubiNativeJSInterface) is added to the WebView, exposing native methods to JS.VPAID Ad Loading:
The WebView loads a URL hosting the VPAID ad player that calls back the native interface for VAST XML and event notifications.Ad Playback and Events:
The JS player requests VAST XML, plays the ad, and notifiesnotifyVideoEnd()ornotifyAdError()on completion or error.FSM Transition:
Upon notification, theTubiVPAIDclient posts a runnable to the UI thread that callsfsmPlayer.removePlayedAdAndTransitToNextState()to continue playback.
Visual Diagram: Class Structure of TubiVPAID
classDiagram
class TubiVPAID {
-static final String TAG
-WebView mVPAIDWebView
-Handler mHandler
-String vastXml
-FsmAdController fsmPlayer
+TubiVPAID(WebView, Handler, FsmPlayer)
+void init(MediaModel)
+void notifyVideoEnd()
+void notifyAdError(int, String)
+String getVastXml()
}
class VPAidWebViewClient {
+boolean shouldOverrideUrlLoading(WebView, String)
+void onReceivedError(WebView, int, String, String)
+void onReceivedError(WebView, WebResourceRequest, WebResourceError)
}
class VPAIDWebChromeClient {
-View mVideoProgressView
+VPAIDWebChromeClient()
+VPAIDWebChromeClient(WebView, View)
+View getVideoLoadingProgressView()
+void onPermissionRequest(PermissionRequest)
}
TubiVPAID --> VPAidWebViewClient : uses
TubiVPAID --> VPAIDWebChromeClient : uses
Summary
The `TubiVPAID` class is a specialized client that enables playback of interactive VPAID video ads within an Android application by embedding a WebView configured for this purpose. It manages the WebView lifecycle, configures necessary settings, and exposes a JavaScript interface for the VPAID ad player to communicate ad playback events and request VAST XML data. The class integrates tightly with the media player's finite state machine (`FsmPlayer`), enabling smooth transitions between content playback and VPAID ads, handling ad completion and error events gracefully, and ensuring the user experience remains seamless. The class's design encapsulates complexity related to WebView handling and JavaScript communication, thereby isolating VPAID ad functionality from the rest of the media player system.