SuperSDK is an Android WebView container SDK providing WebView container, JSBridge, offline package, and cloud control configuration capabilities to help host apps quickly integrate H5 containers.
Optional Module On-Demand Import: If you only integrate the H5 container without requiring login, payment, ads, or push notifications, simply import com.supersdk:supersdk; the core artifact does not transitively import Google Mobile Ads or Firebase.
SNAPSHOT version requires adding an additional snapshot repository (see latest version number in changelog):
The SDK core module will not declare the INTERNET permission for the host app. The android-sdk-implwill merge CAMERA (for <input type="file" capture> photo taking), but will not merge RECORD_AUDIO. The host app must manually add the following to AndroidManifest.xml:
<!-- H5 getUserMedia microphone: The SDK does not merge this; the host app must declare it manually, otherwise the system permission dialog will not appear. -->
<!-- Only when loading http (non-https) resources is required. -->
android:usesCleartextTraffic="true">
...
</application>
</manifest>
CAMERA is still merged by the SDK; the host app does not need to duplicate it. RECORD_AUDIO must be declared by the host app itself (even when using SuperPageActivity with zero Java changes).
Optional modules (Login/Payment/Ads/Push) have their own Manifest and Google backend configurations; see “Optional Capability Module Integration” and “AdService” below.
HTML5 Video Fullscreen Landscape: The SDK’s built-in SuperPageActivity (the fullscreen page opened via IPageController.open()) declares configChanges, so video automatically switches to landscape when entering fullscreen. If you embed AbsSuperPageViewinto your own Activity (via createPageView()), you must declare android:configChanges="orientation|screenSize|keyboardHidden" for that Activity; otherwise, to prevent the SDK from interrupting playback by rebuilding the Activity, it will not trigger landscape rotation (only portrait fullscreen).
WebView microphone and file selection (host app integration)
H5 navigator.mediaDevices.getUserMedia({ audio: true }) and <input type="file"> are handled by the WebChromeClient within the SDK container. Do not replace WebChromeClient / WebViewClient (including getWebView().setWebChromeClient(...)), as doing so will result in the loss of JSBridge, offline package, file selection, and microphone authorization.
Path 1 · Default Fullscreen Page (Zero Java)
IPageController.open() / SuperPageActivity now publicly exposes com.supersdk.api.page.IFileChooserHost (including the independent launchMicrophonePermission), no Java code required. The host app only needs to declare RECORD_AUDIO in its Manifest (see previous section). CAMERA remains merged by the SDK.
Path 2 · Self-wrapped Activity
When embedding createPageView() into your own Activity: implement com.supersdk.api.page.IFileChooserHost, register the launcher in onCreate (before STARTED), and then call setFileChooserHost(this). Do not use reflection, do not cast to the impl type, and do not replace the ChromeClient. Camera and microphone must use independent pending / launchers; they cannot share a single callback slot.
This Android round authorizes audio only. If the H5 also requires camera access (VIDEO_CAPTURE), the entire request is denied. getUserMedia requires an https secure origin.
The project environment corresponds to the env in the top bar of the console (e.g., prod / staging), determining which set of cloud control configurations (settings) the SDK fetches and which environment the telemetry data belongs to. It is no longer an init parameter but an independent runtime state.
Method signature: public static void setAPIEnvironment(String environment) / public static String getAPIEnvironment()
// Set the project environment (can be called before or after init; invalid values throw IllegalArgumentException and do not persist).
SuperSDK.setAPIEnvironment("staging");
// Read the current project environment (returns "prod" if not set; initialization is not required).
Stringenv= SuperSDK.getAPIEnvironment();
Rules and Behaviors:
Value must be 1–10 lowercase letters or digits (^[a-z0-9]{1,10}$); no trimming or case conversion is performed; null is treated as prod.
The SDK does not persist this value: The default prod is used upon process startup. If the host app needs to remember the user’s selection, it must persist the value itself and call setAPIEnvironment after startup.
Runtime switch side effect order: flush existing environment’s queued reporting events → swap values → clear local cache in settings and re-fetch based on new environment → refresh UA of active WebView (affects only subsequent navigation)
After switching, settings fetch automatically includes the env parameter; reporting basic_data.env and the request header X-Super-API-ENV both use the new value; the H5 side reads the new value via getEnv().
This environment is a different dimension from HostConfigService.getSdkApiBaseUrls() (API domain): switching environments does not require and should not change the API domain.
SuperSDKProvider is the bridge through which the host app provides capabilities to the SDK. All Service methods are optional implementations (defaulting to null), to be implemented as needed.
Handle the back key with priority: frontend interception > page history back > exitAction
setSafeArea(int statusBarHeight, int navigationBarHeight)
Set the safe area (physical pixels)
fitSystemWindows(Activity activity)
Automatically adapt to immersive safe area
setImmersiveBottom(boolean immersive)
Whether to immerse at the bottom (default true = content extends under the system navigation bar, existing behavior). Set to false (browser scenario): WebView content shrinks to above the navigation bar + page env(safe-area-inset-bottom)=0 + UA SafeAreaBottom=0, with the third-party site’s bottom bar tightly aligned to the system navigation bar and no extra white space. Applies only to the bottom (top remains immersed); must be called before fitSystemWindows/first load. The host app must be edge-to-edge and not consume the bottom inset upstream.
setOnClosePageListener(Runnable listener)
Set up page close listener (triggered when the frontend calls closePage).
sendBroadcast(String eventKey, String jsonData)
Send a broadcast to the current WebView
destroyView()
Destroy the view and release resources.
getWebView()
Obtain the underlying WebView instance (for direct invocation of native capabilities such as evaluateJavascript/settings); ⚠️ Do not replace WebViewClient/WebChromeClient or reset settings, as this will break the built-in JSBridge and offline package interception.
The SDK supports automatically fetching and installing the latest offline package from a remote site, taking effect without requiring additional integration code from the host app.
Automatic Update Behavior:
Detection Timing: When opening any http(s) page, the SDK silently detects super_meta.json under the root path of the host site in the background during page loading (site-side publishing specifications are available in OFFLINE_PKG_SPEC.md). This process does not block page rendering; a 404 response indicating the site is not integrated is considered a normal state.
Effective Timing: Upon detecting and successfully downloading a new version, it takes effect the next time the host page is loaded, without refreshing the currently open page.
Size Limits: In automatic mode, only packages under 50MB will be automatically downloaded; larger packages are skipped (downloadable only via explicit calls).
Detection Frequency Control: The minimum detection interval for the same host is 30 minutes to avoid request pressure on the site caused by frequent page toggling.
Explicit Trigger Update: The host app can actively call preloadPackage / preloadAllPackages to immediately check for updates, bypassing frequency control and size limits:
// Update successful; the changes will take effect upon the next load of the host page.
}
}
});
// Immediately check and update all installed offline packages.
offlineController.preloadAllPackages(listener);
If the offline package for this host app is not installed locally during the first call, and the remote manifest detection succeeds, the initial installation process will still be triggered (the initial installation takes effect on the next load and does not affect the current page rendering).
Site-side requirements: The site must publish a manifest file compliant with the super_meta.json v1 specification at the root path. The manifest host must be the business domain. The pkg_path can be a site-root-relative path or a full HTTPS URL pointing to an independent CDN (URL query signatures are preserved; full URLs are supported starting from 1.0.0.68-SNAPSHOT). For complete field definitions and zip packaging toolchain constraints (zip -r deflate, no support for stream-based data-descriptor outputs), see OFFLINE_PKG_SPEC.md.
Offline Package Version Binding and Origin Fallback Rules
Page Binding Version: At the start of a page (a single main document load), the SDK selects the offline package version that is installed and verified on the host at that time and binds it to the page, persisting until the page is destroyed or the entire page is reloaded (load / reload / forward/back / full-page navigation). SPA route switching does not change the version.
Updates do not affect running pages: The download, verification, and installation of the new package do not interfere with the old package’s reading. The new version is only used for new pages started after it is ready; the old version files are retained until the last page using them is released.
No Back-to-Origin: After binding a version, all requests under the package host are processed using resources within the package and read exclusively from the bound version. If a resource is missing in the package or the read fails, an error response is returned (HTTP 404 / 500, etc., with the X-Super-Offline-Error header providing the reason, such as resource_missing or read_failed), and the package version, resource path, and reason are logged. No fetch from the online site is performed, and the system will not switch to reading from a newer version.
Business Networking: Requests to other domains proceed normally. APIs and remote media sharing the same domain as the page must be declared in remote_paths within __super_meta.json in the package (see OFFLINE_PKG_SPEC.md).
No valid offline package: The page loads entirely from online resources; packages installed during the loading period are only used for subsequent new pages and are not mixed in mid-process.
getEnv().wappVersion: Returns the package version bound to the current page; an empty string for online pages.
Requests matching remote_paths: Any method directly accessing the network; non-GET/HEAD requests to undeclared same-domain paths return 405.
Require Offline Loading: For pages that must be provided by an offline package, pass PageLoadConfig.setRequireOffline(true) during loading. If this host has no valid offline package, display an error page with a retry button, and trigger an update for this host in the background; do not switch to loading the online page.
Upgrade Compatibility: Offline packages installed by older versions are automatically migrated upon first launch, without requiring a re-download.
Limit: Offline package storage is designed for a single process; please initialize the SDK only in the main process. Requests initiated by Service Workers do not pass through WebViewClient and are not subject to the above rules.
The SDK includes an in-built user feedback submission mechanism (com.supersdk.base.feedback), which shares the same channel as the H5 SuperSDK.submitFeedback: POST /superapi/v2/feedback. In the console, navigate to “Business Operations → User Feedback” to view, search, and mark the processing status by project and environment. The SDK automatically populates spid / env / device_id / platform / app_version / sdk_version / os_version / device_model, while the server records the submission time and user IP; the host app only needs to provide business-specific fields.
FeedbackRequestrequest=newFeedbackRequest("settings", "Crash opening Settings", "The app consistently crashes about one second after opening Settings")
.setSubScene("about") // Optional
.setUserId(currentUserId) // Optional: Business user ID. The SDK does not maintain user identity.
.setExtra(newJSONObject().put("page", "settings")); // Optional: Additional information (≤4KB)
SFeedback.submit(request, new SFeedback.Callback() {
@Override
publicvoidonSuccess(long feedbackId) { /* Already in the library, feedbackId is the server-side record ID */ }
// UNAVAILABLE / PROTOCOL_MISMATCH, or server-side business code (INVALID_REQUEST / NOT_FOUND …)
}
});
Field
Required
Limit
scene
✓
≤64 characters
title
✓
≤200 characters
content
✓
≤5000 characters
subScene
≤64 characters
userId
≤128 characters
extra
JSON object, serialized size ≤4KB
Callbacks are always on the UI thread; all strings are trimmed, and length is counted by character count (server is authoritative). Rate limiting: 10 requests per minute per IP, 600 requests per minute per project. Submissions are not idempotent; the SDK does not automatically retry.
The AB experiment client built into the SDK (com.supersdk.base.experiment) can read group assignments after creating and launching an experiment in the console under “Business Operations → AB Experiments”. Traffic splitting is evaluated server-side based on device_id; the SDK does not implement splitting algorithms. After init completes, the SDK automatically fetches the group assignment for the current device (POST /superapi/v2/experiments/assign), sharing the same set of fallback domains with other SDK requests for round-robin and suenc decoding. In case of HTTP 429 rate limiting, it does not switch to a fallback domain. The result is persisted locally, and the local result is used if the network fails. The aggregation layer entry SuperSDK.getExperiment() returns the same instance.
// Optional: When experimental results are required for the first screen, wait until the first pull of this session completes (or times out) before rendering. The callback runs on the main thread.
SExperiment.awaitReady(2000, ready -> {
// Synchronous read: The first read freezes until the end of the session, and an exposure is reported once by default.
// Audience attributes (keys may optionally include the `attr.` prefix; values are string / number / boolean; `null` indicates removal), re-fetch after 500ms debounce.
Map<String, Object> attrs=new HashMap<>();
attrs.put("vip", true);
SExperiment.setAttributes(attrs);
// By default, only the `default` namespace is loaded; additional namespaces can be appended as needed (up to 10 in total).
// Manual refresh / Listen for result updates (callback on the main thread)
SExperiment.refresh();
SExperiment.addListener(() -> { /* New results have arrived; frozen keys remain unchanged within this session */ });
Method
Description
get(key) / get(key, defaultPayload, expose)
Synchronize returns SExperimentResult{inExperiment, variant, vid, payload, reason}. The first read is frozen until the end of the session; by default, exposure occurs simultaneously. If not participating, payload = defaultPayload ?? {}.
expose(key)
Report exposure for experiments previously read with expose=false; no operation if not previously read.
getAll()
For diagnostics: do not freeze, do not expose (return the frozen value if already frozen).
awaitReady(timeoutMs, callback)
The callback ready=true is triggered after the first pull of this session ends (whether successful, unchanged, or failed); only timeout returns false. If the pull fails and there is no local result, no_result is returned.
setAttributes(map)
Set custom audience attributes attr.* (up to 20, key ≤64, value ≤256 characters); invalid values throw IllegalArgumentException.
addNamespaces(list)
Append the namespace to be loaded and trigger the pull.
refresh()
Manual pull
addListener / removeListener
Result Update Notification
reason values: when participating, it is alloc (normal group) / override (forced whitelist) / rollout (fully rolled out, no exposure); when not participating, it is unknown (no such experiment or not matched) / paused (experiment has been emergency stopped, see below) / not_loaded (experiment’s namespace was not loaded in this session, no freezing) / no_result (no results yet, or more than 7 days since the last successful fetch).
Behavioral Points
Built-in Audience Attributes: platform (android), app_version (host app version), language (e.g., zh-CN), country (device region country code), channel (host channel), install_time (SDK-recorded installation time, milliseconds).
Session and Freezing: Session = process lifecycle; if the app goes to the background and returns to the foreground after more than 30 minutes, it is treated as a new session (clearing the freezing table and deduplicating exposures within the session). Before init, reading returns no_result and freezes until the end of the session. Upon returning to the foreground, if more than 10 minutes have passed since the last successful fetch, it will automatically re-fetch.
Exposure: Event name $exp_exposure (parameters vid, exp_key, exp_run, exp_version, variant, layer_key, reason, rules_version, source; native reads source=native, H5 reads source=h5 via JSB). Deduplicated once per session and once per calendar day for the same group; if queuing fails, the deduplication marker is rolled back and retried on the next read.
Event public parameter exp_vids: When the SDK creates each event, it writes the exposed group IDs into the event’s own parameters (an ascending, comma-separated string, e.g., "10031,10388"; the key is omitted if empty; max 500 IDs). Events created before exposure do not contain these IDs. Host or H5 built-in parameters with the same name (including SReporter.addCommonParam("exp_vids", …)) are discarded. Group IDs that the server no longer returns after the experiment ends are automatically removed upon the next fetch.
Emergency Stop: After the console executes an “Emergency Stop” on an experiment, the next fetched result will immediately invalidate the experiment, even if the current session is frozen: subsequently, get(key) returns a non-participating state (reason=paused, default payload), and no longer triggers exposure; its group ID is removed from the set of exposed groups. Events created thereafter, along with getRequestHeaders() / appendVidsToUrl() and platform request headers, will no longer include it. Listeners receive a single result update notification, and H5 getExperiment reads within the app sync immediately. Even if the experiment is restored within the current session, it remains stopped; only a new session (process restart or background duration exceeding 30 minutes) will re-fetch the configuration.
Project Environment: After calling SuperSDK.setAPIEnvironment(), the system automatically switches to the new environment, re-fetches local records, and re-requests data. Results from different environments and different device_ids are independent of the exposure set.
Shared with In-App H5: The SuperSDK.experiment called by H5 via JSB shares the same results and the same frozen table with native code. For the same experiment, reading once in native and once in H5 results in only a single exposure.
Experiments of type server are grouped by the business backend: the client sends the exposed group ID set of this device (a string identical to exp_vids, sorted in ascending order and comma-separated) to the backend via the request header X-Super-AB-Vids or the query parameter super_ab_vids.
// Request header (returns an empty Map when the collection is empty, omitting the header)
// or query parameters (overwrite existing parameters with the same name, retain other query parameters and #fragment; process as text, also rewrite relative URLs; return as-is only when the URL is empty or the collection is empty)
Return {"X-Super-AB-Vids": "<vids>"}; return an empty Map when the collection is empty.
appendVidsToUrl(url)
Return the URL with super_ab_vids=<vids> appended (e.g., super_ab_vids=10231,10388; commas are not encoded and must match the header value); the SDK will not automatically modify any business URLs.
When to Fix and Expose: When calling the two methods above (or invoking getRequestHeaders / appendVidsToUrl / experiment.fetch via in-app H5), all server-side experiments matched by this device in the loaded namespace are considered read: they are frozen until the end of the session, $exp_exposure is reported once (with source=native for native and source=h5 for H5), the group ID is added to the exposed set, and then the set is returned. Repeated calls within the same session do not trigger duplicate exposure.
get(key) returns an unparticipated result when reading a server-side experiment (reason=unknown, getType() is server), without freezing or exposure, and logs a message suggesting the use of request headers; getAll() lists normally, and SExperimentResult.getType() distinguishes between client and server.
Requests sent by the SDK itself to platform APIs (e.g., api.supersdk.com) automatically include the X-Super-AB-Vids header, but only with the currently exposed set, without triggering fixed experiments or exposure on the server side. When the set is empty, the header is omitted. This header is generated solely by the SDK; a header of the same name injected by the host app via HostNetworkExtensionService is ignored. Requests sent to the host app’s own backend (such as payment receipt) do not include this header.
Precautions:
WebView cannot automatically add request headers to requests initiated by the page itself: Requests from in-app H5 to its own backend must use SuperSDK.experiment.fetch or manually attach the header/parameter.
Cross-origin requests trigger preflight checks: The backend’s Access-Control-Allow-Headers must include X-Super-AB-Vids; if modification is inconvenient, use a query parameter instead.
Backend Read Order: Request headers take precedence, followed by the query parameter super_ab_vids.
Value can be tampered with: For judgments involving price, quota, or entitlement, the backend must call assign with device_id (side: "server") for verification, and cannot rely solely on headers or parameters.
Value is null before the result arrives: The backend processes it using default logic.
Closing Order: The backend first changes the winning logic to the default and deploys it, then ends the experiment in the console.
URL Length: When the number of exposed IDs approaches 500, the query parameters become very long. Some legacy proxies have a 2 KB URL limit, so headers should be prioritized.
// getNetEnv() / ApiEnv is deprecated (SDK never consumed): use the project environment
// SuperSDK.setAPIEnvironment(...); use getSdkApiBaseUrls() for the API domain.
@Override
publicintgetAppVersionCode() {
return BuildConfig.VERSION_CODE;
}
@Override
public String getAppVersionName() {
return BuildConfig.VERSION_NAME;
}
@Override
public String getSdkApiBaseUrl() {
returnnull; // Custom API address; null uses the default.
}
@Override
public String generateDeviceId() {
returnnull; // The host app takes over deviceId generation; null uses the SDK's default logic.
}
}
generateDeviceId - Host app takes over deviceId generation (Optional):
Call only when the SDK needs to generate a new deviceId (on first install, or when the local old value becomes invalid). The locally persisted deviceId continues to be used and remains unaffected (cache priority).
Return a non-empty string: the SDK uses this value as the deviceId and persists it; return null/empty string: follow the SDK’s default generation logic (generate a random UUID and persist it to SP).
Implementation requirements: Synchronous fast return (may be called early in the network request/event reporting path), and multiple calls must return stable values. If the host implementation throws an exception, the SDK will catch it and fall back to default logic.
🔒 Privacy Compliance: The SDK does not readSettings.Secure.ANDROID_ID, nor does it read system device identifiers such as IMEI, MAC, or OAID.
The complete fallback chain for deviceId is memory cache → SP persistent value → host generateDeviceId() → SDK-generated UUID.
Older SDK versions previously wrote ANDROID_ID to SP; after upgrading, these existing values continue to be used (no migration, to avoid device identifier gaps for legacy users).
If the host app’s compliance requirements mandate the complete clearing of existing values, you can take over the generateDeviceId() method and return your own identifier.
The host app implements this interface to take over openPage: receive the URL + configuration and decide how to open it (native page / redirect / custom WebView, etc.). Return true to indicate it has been handled; return false to delegate to the SDK’s default container (selective interception + SDK fallback).
// Match host app route → Open own native page; return true indicates takeover.
if (MyRouter.matchNative(url)) {
MyRouter.openNative(context, url);
returntrue;
}
// Return the rest to the SDK's default container to open.
returnfalse;
}
}
If you want to use the SDK’s WebView container but control the display yourself (embed it in your own Activity/Fragment), simply retrieve the container within openPage without using the SDK’s default page:
// v.setOnClosePageListener(...) can respond to H5's closePage
// Put v into your own container for display, then return true
Container Behavior · target="_blank" / window.open: In H5, clicking <a target="_blank"> links and calling window.open(url) are automatically recognized by the container and uniformly opened as a new page via openPage on the client side (equivalent to appbridge.openPage), routing through the aforementioned NavigationService. No additional adaptation is required in H5; behavior is consistent with iOS.
The host app natively calls loadSplashAd(context, source, placementId, callback) to preload. Upon success, it receives a single-use AdService.ISplashAd. Call show(activity, listener) while the splash screen is still visible and the Activity is available; if the ad is closed or fails to display, proceed to the business page. If the splash screen has already ended, call destroy() to discard the late-arriving ad. The FullScreenAdListener for the splash screen provides events for exposure, click, close, and failure.
The host app determines the maximum wait time for the splash screen, after which it directly navigates to the business page. The adapter package requests the selected ad platform only when explicitly loaded by the host app.
The vendor manifest declarations for GDT and CSJ define different backup strategies. When integrating both SDKs, explicitly set android:allowBackup in the host app manifest. If integrating both SDKs or if the host app’s policy conflicts with a single vendor’s policy, add tools:replace="android:allowBackup" to the same <application> element and declare xmlns:tools="http://schemas.android.com/tools" in the <manifest> element, so that the merged result adopts the host app’s value.
Add com.supersdk:supersdk-ad-gdt with the same version as the core SDK. It transitively depends on com.qq.e.union:union:4.712.1582. After completing the host app privacy consent process, pass the application ID assigned by the Tencent GDT backend. In the following example, adService is a host app field returned by the registered SuperSDKProvider.getAdService().
import com.supersdk.ad.gdt.GdtAdService;
// host app field
privatevolatile AdServiceadService;
// Execute within the host app's privacy consent callback.
Call show(activity, listener) on the splash screen, where the adapter package mounts and unmounts the splash container.
Use the corresponding Youqianhui ad unit ID for each ad format. When using multiple ad providers, the host app’s registered AdService forwards the request to the corresponding adapter package via AdSource. Existing Android H5 Banner and rewarded video entry points can pass adSource: 'GDT'. The Youqianhui adapter package returns NOT_IMPLEMENTED for other ad types.
Merge the adaptation package with GDTFileProvider, whose authority is ${applicationId}.gdt.fileprovider. The manifest of the vendor AAR also declares permissions such as coarse location, querying apps, and installing apps. Before the host app goes live, verify the merged Manifest by channel and actual usage capabilities.
The CSJ adapter for mainland China is com.supersdk:supersdk-ad-csj. The host app must use the same version as the core SDK and set minSdk >= 24. This package includes the CSJ integration com.pangle.cn:ads-sdk-pro:7.8.1.5 and OkHttp required for the download component. Add the vendor repository to the host app’s settings.gradle.kts. CSJ Android Integration Documentation
The host app initializes after completing privacy consent. The adService field below is returned by the host app’s SuperSDKProvider.getAdService(). The Banner template has a default aspect ratio of 2:1, and the size can be configured according to the ad placement selected in the backend. CSJ Banner Template Documentation
import com.supersdk.ad.csj.CsjAdService;
// Execute within the host app's privacy consent callback.
CsjAdService.initialize(context, csjAppId, appName, result -> {
All three formats are loaded using the current Activity, with AdSource.CSJ and the corresponding ad unit ID passed in. Banner’s loadBannerAd and splash’s loadSplashAd are delivered upon successful rendering. Splash ads are requested on the startup page, and the host app can end the wait once business content is loaded. Rewarded video uses loadRewardedAd, triggering onRewarded() only when CSJ confirms the reward is valid. Android H5 Banner and rewarded video can pass adSource: 'CSJ'. Splash Ad · Rewarded Video
AdMob is provided with a complete Android native AdService implementation via the optional artifact supersdk-ad-admob. The module transitively resolves Google Mobile Ads 25.4.0; the core supersdk does not include this dependency.
Host App Integration Checklist (Must Read All):
The host app must do
Requirements
Integrate Provider
Add supersdk-ad-admob; no need to directly add play-services-ads.
Configure App ID
Each white-label product declares its com.google.android.gms.ads.APPLICATION_ID in the <application> tag.
Configure the ad placement
Create Rewarded, Interstitial, Banner, Native, Rewarded Interstitial, and App Open Ad Unit IDs in the AdMob console, and pass them in the corresponding load* calls.
Complete the privacy process
The host app is responsible for handling GDPR/CCPA, child and adolescent advertising policies, and UMP when required; initialization occurs only after consent is obtained.
Initialize and register
After AdMobAdService.initialize succeeds, register the AdService with SuperSDKProvider.
Manage UI/Lifecycle
Call destroy() when the Banner/Native page is exited, replaced, or when a stale callback occurs; provide reward instructions and a skip option before displaying Rewarded Interstitial.
Real device acceptance
Debug: Use Google’s official test IDs. Before production release, verify the loading, display, failure, reward, and resource release of six ad types.
The module handles Google Ads dependencies, network permissions, main thread scheduling, initialization idempotency, error mapping, duplicate terminal state protection, and Native default templates; it does not create AdMob backend resources for the host app, save business IDs, execute privacy consent, or determine page lifecycle. See the module-level complete documentation in the repository packages/android-sdk-ad-admob/README.md.
Test period available Google official test App ID: ca-app-pub-3940256099942544~3347511713
For multi-white-label projects, it is recommended to inject via manifest placeholders based on flavor/build type to prevent cross-contamination between different products or test/production environments:
Use android:value="${ADMOB_APP_ID}" in the manifest. The manifest must contain the App ID. You can store ad unit IDs in BuildConfig or remote configuration and pass the appropriate ID to each load* call.
Complete your host app’s own GDPR/CCPA/children and teens advertising consent processes first, then initialize the Provider. Create and register the service only after a successful callback; the callback uses only SuperSDK’s SuperResult and does not leak Google SDK types to the host app:
AdMobAdService.initialize(getApplicationContext(), result -> {
AdMobAdService.initialize is idempotent for concurrent and repeated calls; calling any load* method before initialization returns NOT_INITIALIZED. The Provider does not include App ID or ad placement ID by default and does not automatically handle privacy consent.
Capability Boundaries:
Call entry
Supported Types
Android native AdService
Rewarded, Interstitial, Banner, Native, Rewarded Interstitial, App Open (six types)
Native uses the Provider’s built-in default NativeAdView asset set, mounting via INativeAd.showAtContainer(container). The host app must call destroy() when exiting the page.
For Rewarded Interstitial, the host app must display an intro screen that clearly explains the reward content and allows users to skip it before calling show(...). The Provider only responds to the host’s explicit show call and will not generate or replace this business UI.
Add an app to obtain the App ID (fill in the APPLICATION_ID above).
Create ad unit
Create an Ad Unit ID for each ad placement; the four Android H5 types are specified by adUnitId, while Native and App Open are passed in by the host app.
Test ads
Use official test ad units during development to avoid account suspension due to invalid traffic.
Allows the host app to append query parameters and request headers to SDK internal network requests (settings / event reporting / attribution / short links, etc.). All interfaces are default methods; they take effect only when implemented, so existing integrations require no changes.
Starting from 1.0.0.65-SNAPSHOT, the SDK automatically includes X-Package-Name (the host app’s package name) without configuration. Backup line retries also include it; empty values are skipped. The host app’s network extension cannot override this header.
publicclassMyProviderimplementsSuperSDKProvider {
@Override
public HostNetworkExtensionService getHostNetworkExtensionService() {
returnnewHostNetworkExtensionService() {
@Override
public Map<String, String> getExtraQueryParams(SuperRequestContext context) {
// Enable response obfuscation: The SDK does not append this parameter by default.
return Collections.singletonMap("suenc", "1");
}
@Override
public Map<String, String> getExtraHeaders(SuperRequestContext context) {
SuperRequestContext provides getUrl(), getPath(), and getHost(), enabling the host app to return responses conditionally based on request parameters.
Merge Rules (Enforced by the SDK; cannot be bypassed by the host app):
SDK-native query / header priority — query names match exactly, header names match case-insensitively. For example, if the SDK sets X-Super-API-ENV, the host app returning x-super-api-env will not override it.
Authorization, Cookie, and other authentication credential headers are not accepted for injection via this interface.
Invalid items (empty key/value, key contains illegal characters, header name does not comply with token specifications) are skipped individually, while the rest take effect as normal.
All thrown exceptions are caught and do not block the SDK’s main flow.
Read in real-time for each request; the SDK does not cache return values—the host app can change the returned content at any time.
Two methods are synchronously invoked on the thread that initiates the request; the implementation must return quickly and must not block.
Download-type requests (offline packages, downloadFile) and direct payment receipt delivery do not inject query parameters, but header extensions still apply.
The server encodes the JSON response body using a custom Base64 table when the request includes ?suenc=1 and returns X-Su-Enc: b64t1. The SDK internally automatically decodes the response (including non-2xx error responses), so the host app does not need to intervene—simply inject suenc=1 as described above.
⚠️ Only for reducing the effectiveness of generic keyword scanning, not for encryption: Does not provide confidentiality, tamper resistance, or replay protection.
If the host app initiates a suenc request, you can invoke the SDK’s decoding capability:
// Query the locally supported codecs and decide whether to send suenc=1
Decoding failures are uniformly treated as request failures; never fall back to reading plaintext—that is precisely the downgrade the protocol aims to prevent.
If the request includes suenc=1 but the response lacks X-Su-Enc, the SDK marks the route as failed and automatically switches to the next baseUrl.
The encoding table never changes after SDK release; new tables always use a new codec key, so codec must be obtained from the response header rather than hardcoded.
The following modules are optional and should be integrated based on the host app’s business requirements. Each module’s integration involves three steps: ① Add dependencies · ② Register Provider · ③ Configure Google / Firebase backend. (See the “AdService” section above for AdMob integration.)
Based on Android Credential Manager + Sign in with Google, return the Google-issued ID Token, which is then verified by the business backend to exchange for the business login session.
.addProvider(newGoogleAuthProvider(SERVER_CLIENT_ID)) // provider name = "google"
.build();
@Override
public LoginService getLoginService() {
return loginService;
}
SERVER_CLIENT_ID is the OAuth Client ID for the Web application type (not the Android type), and it is also the aud of the returned ID Token.
The Manifest module is empty, requiring no additional permissions (handled internally by Credential Manager), relying solely on the public INTERNET permission.
Fill in the application information and Scope (at least email / profile)
Create Web OAuth Client ID
i.e., SERVER_CLIENT_ID in the code; when the business backend validates the ID Token, the aud claim must equal it.
Create Android OAuth Client ID
Provide package name + SHA-1 signature fingerprint (one for debug and one for release). Credential Manager requires this fingerprint to be registered when fetching Google credentials; otherwise, the callback returns ERROR or the account cannot be retrieved.
Get SHA-1: ./gradlew signingReport (or keytool -list -v -keystore <keystore>).
Based on Google Play Billing Library. H5 queries the current account’s available subscription offers and initiates the purchase via SuperSDK.pay.*, while the native side integrates with Google Play through GooglePayProvider (provider name "google_play").
.addProvider(newGooglePayProvider(context)) // provider name = "google_play"
.build();
@Override
public PayService getPayService() {
return payService;
}
The com.android.vending.BILLING permission is declared by the module Manifest and automatically merged; the host app does not need to manually add it.
The Android public query DTOs are SubscriptionOfferInfo and SubscriptionPricingPhase; both new query methods of PayProvider and PayService have a default NOT_SUPPORTED implementation, ensuring compatibility with legacy host apps and providers.
Starting from 1.0.0.67-SNAPSHOT, host app-level requireProfileId validation can be enabled via new GooglePayProvider(context, true). Once enabled, if the profileId is missing from the purchase parameters, INVALID_PARAMS will be returned before initiating the charge. A single-argument constructor leaves this validation disabled by default, preserving existing behavior.
The accountId in the purchase parameters is passed to the receipt interface along with the native payment credentials, enabling the business service to associate the account; the project identity header X-Aid remains unchanged.
③ Query eligible offers for the current account and make a purchase:
offerId: selected.offerId, // The default base plan is null.
accountId: accountHash,
profileId: orderTokenUuid
}
});
The query result contains only SubscriptionOfferDetails returned by Play Billing for the current account, without concatenating the full Play Console catalog or filtering via Settings.
The query response will not include offerToken. During purchase, the Provider will re-query ProductDetails, precisely matching productId + basePlanId + nullable offerId, and only pass the latest token to setOfferToken() within the Native environment.
A change in eligibility returns OFFER_UNAVAILABLE without silently switching to another price. Other subscription errors: PRODUCT_NOT_FOUND, BILLING_UNAVAILABLE, QUERY_FAILED, USER_CANCELLED, PURCHASE_FAILED.
The public behavior of the legacy INAPP and queryProducts() remains unchanged; business order creation, entitlement mapping, server-side order verification/acknowledge/RTDN are out of scope for this module.
Must be uploaded to at least the internal testing track with the same package name + signature (Billing only works with signatures from Play Store installations; local debug direct installation cannot be tested).
Create product
Monetize → Products → In-App Purchases / Subscriptions, the product ID must match the one passed by the H5 page.
Configure test accounts
Add License testers to test purchases using sandbox accounts without incurring real charges.
Server-side fulfillment (recommended)
Configure Real-time developer notifications (RTDN) + Cloud Pub/Sub + Play Developer API to use the server as the source of truth for idempotent fulfillment — the complete architecture is detailed in the JSSDK documentation “IAP Recommended Architecture”.
Based on Firebase Cloud Messaging. The host app adds a dependency and implements a getter. After the app starts, this device automatically registers to the “Push → Devices” page under the current “Project × Environment” in the console, receives push notifications sent from the console, opens the specified page upon click, and is counted as “Opened”. H5 pages query status, request permissions, set tags, and set user IDs via SuperSDK.push.*. For complete product documentation, server-side sending API, and console usage, see SuperPush Special Article.
① Dependencies (minSdk ≥ 23, matching the version of com.supersdk:supersdk):
app/build.gradle.kts
// root build.gradle.kts
plugins { id("com.google.gms.google-services") version "4.4.2" apply false }
Place the google-services.json downloaded from the Firebase Console into the app/ directory (do not commit to git). The external package carries firebase-messaging (25.1.3) as a runtime dependency (do not include it in the host’s compile classpath). Do not declare different versions; only the method in ⑤ “Custom Service” requires the host app to declare the same version. It depends only on the SDK’s api + base layers. Host apps that do not integrate push notifications will not be pulled into Firebase.
The external package’s Manifest declares the POST_NOTIFICATIONS permission, SuperFirebaseMessagingService, and the click-through activity SuperPushTrampolineActivity; the host app does not need to manually add them.
② Register Provider — Implement getPushService() in SuperSDKProvider (default returns null = no push integration):
.addProvider(newFirebasePushProvider(applicationContext)) // v1 takes only the first provider.
// .allowUrlScheme("myapp") // Optional: Allow custom schemes other than http(s) to be opened on click
.build();
@Override
public PushService getPushService() {
return pushService;
}
SuperSDK.init must be called in Application.onCreate; the SDK parses the getter once during initialization and caches it, so SuperSDK.getPushService() returns the same instance (returns null if not wired or not initialized, without throwing an exception). Push services are initialized only in the main process.
In non-prod environments, call SuperSDK.setAPIEnvironment(env)before init or immediately after init: the initial registration is deferred to the next main thread tick, and switching the environment immediately after init takes effect for the initial registration; subsequent environment switches will trigger a re-registration.
Automatic registration timing: upon first obtaining the token, token refresh, environment switch, value change in setTags/setUserId, permission result return, and visibility change notification during cold start and when returning to the foreground. The same fingerprint will not be sent repeatedly within 24 hours; if a failure occurs, no retry is performed within the current process, but the retry is deferred to the next trigger point.
③ Optional call (calling before init is safe: setListener takes effect immediately, setTags/setUserId queues for playback after init, requestPermission returns to NOT_INITIALIZED):
PushServicepush= SuperSDK.getPushService();
push.requestPermission(activity, result -> { // Android 13+ displays the system notification permission dialog; <13 directly returns the current status.
push.getPermissionStatus(); // PROMPT = 13+ and system dialog has not been displayed yet
push.setTags(Arrays.asList("vip", "beta")); // ≤10 items, each ≤32 characters; null / empty list = clear; throw IllegalArgumentException if out of bounds
@OverridepublicbooleanonMessage(PushMessage m) { returnfalse; } // Front-end receives: true = self-displayed; SDK does not trigger system notifications.
@OverridepublicbooleanonOpened(PushMessage m) { returnfalse; } // User clicks; true = full takeover, SDK will no longer open the URL
The timing for permission requests should be placed after the user understands the value of push notifications (e.g., when completing a key operation for the first time), and should not be triggered in Application.onCreate.
④ Default Behavior and Two Override Interfaces
Scenario
Default behavior
Takeover Method
Background / Killed
The system displays content based on the notification.
Non-manageable (FCM behavior)
Received in the foreground
The optional adapter uses the supersdk_push_default channel for display (title / body / large image); onMessage and H5 push.message are triggered simultaneously.
onMessage returns true to suppress the notification.
Click (click.type=open_url)
Launch the host Activity via the transit Activity → Send a receipt to the server (≤2 seconds) → Open using the authoritative url returned by the server via NavigationService.openPage (if the host app implements the interface, use host routing; otherwise, use the SDK’s default container page); stack order main Activity → container page.
onOpened returns true to take full control; if only changing “how to open the page,” implement NavigationService (see the section above).
Click receipt unreachable (offline / weak network / server exception)
Only launch the main Activity, do not open URL; onOpened / push.opened / $push_open execute as usual, verified=false
If the host app opens the url in the message within onOpened itself, check message.isVerified() first (PushMessage includes isVerified() / getOpenedAt(); Native getStatus().getLastOpened() also includes verified). Otherwise, a malicious app on the same device could forge a click intent to open any arbitrary page.
User denied permission / disabled notifications
Still registered (registration entity enabled=false), getStatus().permission correctly returns DENIED / PROMPT; not displayed in the foreground but callbacks proceed normally.
After the user enables it in system settings, the next evaluation will automatically refresh.
⑤ Already have your own FirebaseMessagingService — Remove the Service from the manifest of the external package and forward the two callbacks; keep the transit Activity. Two prerequisites: ① The host build.gradle must independently declare the same versionimplementation("com.google.firebase:firebase-messaging:25.1.3") (the external package carries it as a runtime dependency, not included in the host’s compile classpath; otherwise, extends FirebaseMessagingService will fail to compile); ② This Service must not declare android:process (the SDK installs only in the main process; messages and tokens in child processes will be dropped, with one WARN … push not attached in process <name> log per process in logcat):
@OverridepublicvoidonMessageReceived(RemoteMessage m) { FirebasePushProvider.handleMessage(m); }
⑥ Unconnected State: When the dependency is added but getPushService() returns null, the Service and transit Activity in the optional adapter perform no-op (the first message/token per process is dropped and logged as WARN SuperPush … push not attached in process <process name>, then downgraded to debug)—no registration, no routing, no reporting; clicks only forward to launch the host app; Firebase’s native behavior (token retrieval, system display) remains unaffected by the SDK. H5 getStatus() returns { supported: false }, while other push.* calls return to UNSUPPORTED. The host app behavior without the dependency remains exactly as before.
⑦ Logging and Troubleshooting: All push logs share the TAG SuperPush, with the real device adb logcat -s ss-SuperPush. Successful registration prints register ok device_id=… env=… token=…(last 6 characters), while failures print ERROR (including HTTP status and server code). Logs do not contain the full token, user_id, or tags values. getStatus().lastError closed set: TOKEN_UNAVAILABLE (Firebase not configured / token unavailable), NOT_FOUND (spid / environment not registered in the console), INVALID_REQUEST, RATE_LIMITED, NETWORK_ERROR, UNAVAILABLE. During environment switching, if FCM refreshes the token, the old environment retains the old token; subsequent sends to the old environment for that device will be marked as unregistered. Switching back automatically re-registers and restores the state — this is expected behavior, not an integration issue.
⑧ Security Boundaries: user_id and tags are self-declared by the host app; the server performs no identity verification. User ID-based targeting is not identity authentication; do not use it to deliver sensitive content. The data payload is delivered to the device as-is; do not include any secrets.
Enter the package name (consistent with applicationId), and download google-services.json to app/.
Generate service account private key
”Project Settings → Service Account → Generate New Private Key”; the JSON file must be uploaded by the console administrator under “Push Settings”. The app side does not need it.
Same Firebase project
The google-services.json in the host app and the service account uploaded to the console must belong to the same Firebase project; otherwise, the reporting side will return SENDER_ID_MISMATCH.
Initialization Timing: SuperSDK.init() must be called before using any SDK features; it is recommended to call it within Application.onCreate().
Lifecycle: The SDK automatically perceives the Activity lifecycle via onWindowVisibilityChanged internally, without requiring manual dispatching.
Back Key Handling: Use handleBackPressed(exitAction) to handle the back key; the SDK automatically manages frontend interception and page history back navigation.
Destroy: When an Activity is destroyed, you must call pageView.destroyView() to release resources.
Thread Safety: SDK UI operations are automatically switched to the main thread; the host app requires no additional handling.
Offline package: The SDK supports built-in offline packages, automatically matching local resources when loading a URL.