# SuperSDK for Android
> **Version: dev** | **Stability: In Development** — Content subject to change; for internal reference only
## Overview
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.
## Environment requirements
| Project | Requirements |
|------|------|
| minSdkVersion | 23 (Android 6.0) |
| compileSdkVersion | 35 or higher (this repository uses 36) |
| Java version | Java 11+ |
| Dependencies | AndroidX |
## Integration methods
### Maven dependency (recommended)
```groovy
dependencies {
// Required: SDK core (container / JSBridge / offline package / cloud control)
implementation 'com.supersdk:supersdk:VERSION'
// Optional: Google Sign-In (see "Optional Capability Module Integration · Google Sign-In")
implementation 'com.supersdk:supersdk-auth-google:VERSION'
// Optional: Google Pay in-app purchases (see "Optional Capability Module Integration · Google Pay")
implementation 'com.supersdk:supersdk-pay-google:VERSION'
// Optional: AdMob ad provider (see "AdService · AdMob Integration")
implementation 'com.supersdk:supersdk-ad-admob:VERSION'
// Optional: Tencent GDT (Tencent GDT)
implementation 'com.supersdk:supersdk-ad-gdt:VERSION'
// Optional: Domestic CSJ (minSdk 24, and add the vendor repository below)
implementation 'com.supersdk:supersdk-ad-csj:VERSION'
// Optional: Push notifications (Firebase Cloud Messaging, see "Optional Capability Module Integration · Push")
implementation 'com.supersdk:supersdk-push-firebase:VERSION'
}
```
> **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](https://www.superplatform.ai/en/changelog.md)):
> ```groovy
> repositories {
> maven { url 'https://central.sonatype.com/repository/maven-snapshots/' }
> }
> ```
### AAR manual integration
1. Place `supersdk-VERSION.aar` into the `libs/` directory of the project.
2. Add to `build.gradle`:
```groovy
dependencies {
implementation fileTree(dir: 'libs', include: ['*.aar'])
}
```
### Required AndroidManifest configuration
The SDK core module **will not** declare the `INTERNET` permission for the host app. The `android-sdk-impl` **will merge `CAMERA`** (for `` photo taking), but **will not merge `RECORD_AUDIO`**. The host app **must** manually add the following to `AndroidManifest.xml`:
```xml
android:usesCleartextTraffic="true">
...
```
> `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 `AbsSuperPageView` **into 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 `` 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.
```java
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.supersdk.SuperSDK;
import com.supersdk.api.page.AbsSuperPageView;
import com.supersdk.api.page.FileChooserResultCallback;
import com.supersdk.api.page.IFileChooserHost;
import com.supersdk.api.page.PageLoadConfig;
import com.supersdk.api.page.PermissionResultCallback;
public class MyWebActivity extends AppCompatActivity implements IFileChooserHost {
private AbsSuperPageView pageView;
private ActivityResultLauncher fileChooserLauncher;
private ActivityResultLauncher cameraPermissionLauncher;
private ActivityResultLauncher microphonePermissionLauncher;
@Nullable private FileChooserResultCallback pendingFileChooserCallback;
@Nullable private PermissionResultCallback pendingCameraCallback;
@Nullable private PermissionResultCallback pendingMicrophoneCallback;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fileChooserLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
FileChooserResultCallback cb = pendingFileChooserCallback;
pendingFileChooserCallback = null;
if (cb != null) cb.onResult(result.getResultCode(), result.getData());
});
cameraPermissionLauncher = registerForActivityResult(
new ActivityResultContracts.RequestPermission(),
granted -> {
PermissionResultCallback cb = pendingCameraCallback;
pendingCameraCallback = null;
if (cb != null) cb.onResult(Boolean.TRUE.equals(granted));
});
microphonePermissionLauncher = registerForActivityResult(
new ActivityResultContracts.RequestPermission(),
granted -> {
PermissionResultCallback cb = pendingMicrophoneCallback;
pendingMicrophoneCallback = null;
if (cb != null) cb.onResult(Boolean.TRUE.equals(granted));
});
pageView = SuperSDK.getPageController().createPageView();
setContentView(pageView);
pageView.setFileChooserHost(this);
pageView.load("https://example.com", new PageLoadConfig("https://example.com"));
}
@Override
public void launchFileChooser(@NonNull Intent intent, @NonNull FileChooserResultCallback callback) {
pendingFileChooserCallback = callback;
fileChooserLauncher.launch(intent);
}
@Override
public void launchCameraPermission(@NonNull PermissionResultCallback callback) {
pendingCameraCallback = callback;
cameraPermissionLauncher.launch(Manifest.permission.CAMERA);
}
@Override
public void launchMicrophonePermission(@NonNull PermissionResultCallback callback) {
pendingMicrophoneCallback = callback;
microphonePermissionLauncher.launch(Manifest.permission.RECORD_AUDIO);
}
@NonNull
@Override
public Context getHostContext() {
return getApplicationContext();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (pageView != null) pageView.destroyView();
}
}
```
> 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.
---
## Initialization
Initialize the SDK in `Application.onCreate()`:
```java
import com.supersdk.SuperSDK;
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// Replace ab12cd34 with the real spid issued by the SuperSDK console.
SuperSDK.init(this, "ab12cd34", new MySDKProvider());
}
}
```
**Parameter Description:**
| Parameter | Type | Description |
|------|------|------|
| context | Context | Application Context |
| spid | String | 8-character lowercase alphanumeric project ID issued by the console |
| provider | SuperSDKProvider | Host app implementation of the service provider |
---
## Project Environment (API Environment)
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()`
```java
// 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).
String env = 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.
---
## Implement SuperSDKProvider
`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.
```java
import com.supersdk.api.SuperSDKProvider;
public class MySDKProvider extends SuperSDKProvider {
private final MyHostConfigService hostConfigService = new MyHostConfigService();
@Override
public HostConfigService getHostConfigService() {
return hostConfigService;
}
@Override
public EventService getEventService() {
return null; // Implement on demand
}
@Override
public LoginService getLoginService() {
return null; // Implement on demand
}
@Override
public HostMethodService getHostMethodService() {
return null; // Implement on demand
}
@Override
public NavigationService getNavigationService() {
return null; // Implement on demand
}
@Override
public AdService getAdService() {
return null; // Implement on demand
}
@Override
public PayService getPayService() {
return null; // Implement on demand (see "Optional Capability Module Integration · Google Pay")
}
@Override
public PushService getPushService() {
return null; // Implement on demand (see "Optional Capability Module Integration · Push").
}
@Override
public INativeBlockProvider getNativeBlockService() {
return null; // Implement on demand
}
}
```
---
## Core API
### IPageController - Page Management
Obtained via `SuperSDK.getPageController()`.
```java
IPageController pageController = SuperSDK.getPageController();
// Open full-screen page
pageController.open("https://example.com");
// Create a PageView and embed it into your own layout.
AbsSuperPageView pageView = pageController.createPageView();
```
| Method | Description |
|------|------|
| `open(String url)` | Open URL in a new full-screen page |
| `createPageView()` | Create an embeddable PageView instance |
### AbsSuperPageView - Page View
`AbsSuperPageView` extends `FrameLayout` and serves as the core container view of the SDK.
```java
AbsSuperPageView pageView = SuperSDK.getPageController().createPageView();
// Add to layout
container.addView(pageView);
// Load URL
pageView.load("https://example.com", new PageLoadConfig("https://example.com"));
// Adapt to immersive safe area (automatically obtain status bar and navigation bar heights)
pageView.fitSystemWindows(this);
// Handle the back button (priority: frontend interception > page history back > exitAction)
@Override
public void onBackPressed() {
pageView.handleBackPressed(() -> super.onBackPressed());
}
// Destroy (mandatory to call)
@Override
protected void onDestroy() {
super.onDestroy();
pageView.destroyView();
}
```
| Method | Description |
|------|------|
| `load(String url, PageLoadConfig config)` | Load URL |
| `reload()` | Reload current page |
| `stopLoading()` | Stop loading |
| `canGoBack()` | Can I go back? |
| `goBack()` | Go back one page |
| `handleBackPressed(Runnable exitAction)` | 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. |
### IOfflineController - Offline Package Management
Obtained via `SuperSDK.getOfflineController()`.
```java
IOfflineController offlineController = SuperSDK.getOfflineController();
// Query all offline package statuses
List packages = offlineController.getAllPackages();
// Query specified offline package
OfflinePackageState state = offlineController.getPackage("example.com");
// Update specified offline package (pull remote manifest from site → download and install, see "Offline Package Remote Update" section)
offlineController.preloadPackage("example.com", new OfflineUpdateListener() {
@Override
public void onProgress(@NonNull String host, int progress) {
// Download progress 0-100
}
@Override
public void onComplete(@NonNull OfflineUpdateResult result) {
if (result.isSuccess()) {
// Update successful
}
}
});
// Update all offline packages
offlineController.preloadAllPackages(listener);
```
#### OfflinePackageState
Information about the installed offline package; the currently installed version is still returned during the download of a new version.
| Method | Return Type | Description |
|------|----------|------|
| `getHost()` | String | Offline package domain identifier |
| `getLocalVersion()` | String | local version number |
| `getSource()` | Source | Source: `ASSETS` (built-in) / `DOWNLOAD` (cloud download) / `MANUAL` (external manual installation) |
#### OfflineUpdateResult
| Method | Return Type | Description |
|------|----------|------|
| `getHost()` | String | Offline package domain identifier |
| `getCode()` | Code | Result code (see table below) |
| `getMessage()` | String | Result description information |
| `getNewVersion()` | String | Updated version number |
| `isSuccess()` | boolean | Whether successful (SUCCESS or ALREADY_UP_TO_DATE) |
**Code Enum Values:**
| Code | Description |
|------|------|
| `SUCCESS` | Update successful |
| `ALREADY_UP_TO_DATE` | Already the latest version |
| `DOWNLOAD_FAILED` | Download failed |
| `VERIFY_FAILED` | Validation failed |
| `EXTRACT_FAILED` | Decompression failed |
| `PACKAGE_NOT_CONFIGURED` | Offline package not configured |
| `ALREADY_UPDATING` | Updating |
| `UNKNOWN_ERROR` | Unknown error |
#### Offline package remote update
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`](https://www.superplatform.ai/en/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:
```java
IOfflineController offlineController = SuperSDK.getOfflineController();
// Immediately check and update the offline package for the specified host (bypassing frequency control and the 50MB limit).
offlineController.preloadPackage("example.com", new OfflineUpdateListener() {
@Override
public void onProgress(@NonNull String host, int progress) {
// Download progress 0-100
}
@Override
public void onComplete(@NonNull OfflineUpdateResult result) {
if (result.isSuccess()) {
// 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`](https://www.superplatform.ai/en/offline-pkg-spec.md).
#### Offline Package Version Binding and Origin Fallback Rules
> Starting from `1.0.0.69-SNAPSHOT`.
- **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`](https://www.superplatform.ai/en/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.
```java
pageView.load(url, new PageLoadConfig(url).setRequireOffline(true));
```
- **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.
### SFeedback - User Feedback
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.
```java
import com.supersdk.base.feedback.FeedbackRequest;
import com.supersdk.base.feedback.SFeedback;
FeedbackRequest request = new FeedbackRequest("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(new JSONObject().put("page", "settings")); // Optional: Additional information (≤4KB)
SFeedback.submit(request, new SFeedback.Callback() {
@Override
public void onSuccess(long feedbackId) { /* Already in the library, feedbackId is the server-side record ID */ }
@Override
public void onFailure(@NonNull String code, @NonNull String message) {
// code: INVALID_ARGUMENT (local validation failed, request not sent) / NETWORK_ERROR / RATE_LIMITED /
// 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.
### SExperiment - AB Experiment
> Starting from `1.0.0.69-SNAPSHOT`.
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.
```java
import com.supersdk.base.experiment.SExperiment;
import com.supersdk.base.experiment.SExperimentResult;
// 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.
SExperimentResult result = SExperiment.get("paywall_price");
if (result.isInExperiment()) {
String price = result.getPayload().optString("price", "9.9");
// result.getVariant() / result.getVid()
}
});
// Read first, then trigger exposure only when actually displayed.
SExperimentResult r = SExperiment.get("new_onboarding", new JSONObject().put("steps", 3), false);
// ... the user actually saw the new flow
SExperiment.expose("new_onboarding");
// Audience attributes (keys may optionally include the `attr.` prefix; values are string / number / boolean; `null` indicates removal), re-fetch after 500ms debounce.
Map 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).
SExperiment.addNamespaces(Collections.singletonList("checkout"));
// 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_id`s 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.
#### Server experiment
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`.
```java
// Request header (returns an empty Map when the collection is empty, omitting the header)
Map abHeaders = SExperiment.getRequestHeaders();
// 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)
String url = SExperiment.appendVidsToUrl("https://api.example.com/feed?page=1");
```
| Method | Description |
|------|------|
| `getRequestHeaders()` | Return `{"X-Super-AB-Vids": ""}`; return an empty Map when the collection is empty. |
| `appendVidsToUrl(url)` | Return the URL with `super_ab_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:
1. **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.
2. **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.
3. **Backend Read Order**: Request headers take precedence, followed by the query parameter `super_ab_vids`.
4. **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.
5. **Value is null before the result arrives**: The backend processes it using default logic.
6. **Closing Order**: The backend first changes the winning logic to the default and deploys it, then ends the experiment in the console.
7. **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.
### INativeBlockProvider - Native Block
Native Block allows H5 pages to embed native views provided by the host app (such as ads, video players, etc.).
```java
// 1. Implement INativeBlockProvider
public class MyNativeBlockProvider implements INativeBlockProvider {
@Override
public boolean supports(String blockType) {
return "ad-banner".equals(blockType) || "video-player".equals(blockType);
}
@Override
public View createBlockView(Context context, String blockId, String blockType, String config) {
switch (blockType) {
case "ad-banner":
return createAdView(context, config);
case "video-player":
return createVideoView(context, config);
default:
return null;
}
}
@Override
public void onBlockShow(String blockId, View view) {
// Block enters the visible area
}
@Override
public void onBlockHide(String blockId, View view) {
// Block leaves the visible area
}
@Override
public void onBlockDestroy(String blockId, View view) {
// The block is destroyed, and resources are released.
}
}
// 2. Register Provider (choose one of the following)
// Method A: via SuperSDKProvider
@Override
public INativeBlockProvider getNativeBlockService() {
return new MyNativeBlockProvider();
}
// Method B: Dynamic Configuration
SuperSDK.setNativeBlockProvider(new MyNativeBlockProvider());
```
| Method | Description |
|------|------|
| `supports(String blockType)` | Does it support specifying a type? |
| `createBlockView(Context, String, String, String)` | Create native view |
| `onBlockShow(String, View)` | Block enter visible area callback |
| `onBlockHide(String, View)` | Block leave visible area callback |
| `onBlockDestroy(String, View)` | Block destruction callback |
---
## Service Agreement Terms
### HostConfigService - Host Configuration
Provide basic configuration information for the host app.
```java
public class MyHostConfigService implements HostConfigService {
@Override
public String getAppChannel() {
return "GooglePlay"; // Channel ID
}
// getNetEnv() / ApiEnv is deprecated (SDK never consumed): use the project environment
// SuperSDK.setAPIEnvironment(...); use getSdkApiBaseUrls() for the API domain.
@Override
public int getAppVersionCode() {
return BuildConfig.VERSION_CODE;
}
@Override
public String getAppVersionName() {
return BuildConfig.VERSION_NAME;
}
@Override
public String getSdkApiBaseUrl() {
return null; // Custom API address; null uses the default.
}
@Override
public String generateDeviceId() {
return null; // 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 read** `Settings.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.
### EventService - Event Reporting
Receive events generated by the SDK; the host app can integrate with its own tracking platform.
```java
public class MyEventService implements EventService {
@Override
public void onEvent(@NonNull Event evt) {
String eventName = evt.getEventName();
Map params = evt.getParams();
// Report to your own tracking platform
Analytics.track(eventName, params);
}
}
```
### LoginService - Login Service
When an H5 page requires login, the SDK invokes this service.
```java
public class MyLoginService implements LoginService {
@Override
public void requestLogin(@NonNull Context context,
@NonNull LoginResultCallback callback) {
// Launch the host app's login flow
LoginManager.login(context, result -> {
if (result.isSuccess()) {
HostLoginInfo loginInfo = new HostLoginInfo(result.getAuthCode());
callback.onResult("SUCCESS", "Signed in", loginInfo);
} else {
callback.onResult("FAIL", "Sign-in failed", null);
}
});
}
}
```
**HostLoginInfo:**
| Method | Type | Description |
|------|------|------|
| `getAuthCode()` | String | Login authorization code |
| `getExtraAuthInfo()` | HostLoginExtraAuthInfo | Extended Login Information (Optional) |
**HostLoginExtraAuthInfo:**
| Method | Type | Description |
|------|------|------|
| `getLoginType()` | String | Login Method |
| `getToken()` | String | Token |
| `getRefreshToken()` | String | Refresh Token |
| `getRefreshTokenExpiresAt()` | long | Refresh Token expiration time |
| `isFirstLogin()` | boolean | Is it the first login? |
| `getExtra()` | JSONObject | Additional extended data |
### HostMethodService - Host Custom Method
Allow H5 to invoke host app custom methods to implement business extensions.
```java
public class MyHostMethodService implements HostMethodService {
@Override
public void invokeAsync(String methodName, @Nullable JSONObject param,
@NonNull HostMethodCallback callback) {
switch (methodName) {
case "getUserInfo":
JSONObject result = new JSONObject();
result.put("name", "Alex");
callback.onResult("SUCCESS", "", result);
break;
default:
callback.onResult("NOT_FOUND", "Method not found", null);
break;
}
}
}
```
### NavigationService - Takes over openPage (URL routing)
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).
```java
public class MyNavigationService implements NavigationService {
@Override
public boolean openPage(Context context, String url, PageConfig config) {
// Match host app route → Open own native page; return true indicates takeover.
if (MyRouter.matchNative(url)) {
MyRouter.openNative(context, url);
return true;
}
// Return the rest to the SDK's default container to open.
return false;
}
}
```
> 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:
> ```java
> AbsSuperPageView v = SuperSDK.getPageController().createPageView();
> v.load(url, null);
> // 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 `` 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.
### AdService - Ad Service
Provides ad loading and display capabilities.
```java
public class MyAdService implements AdService {
@Override
public void loadNativeAd(@NonNull Context context, @NonNull AdSource adSource,
@NonNull String adUnitId, @NonNull NativeAdLoadCallback callback) {
// Load native ads
}
@Override
public void loadRewardedAd(@NonNull Context context, @NonNull AdSource adSource,
@NonNull String adUnitId, @NonNull SuperCallback callback) {
// Load rewarded video ads
}
@Override
public void loadInterstitialAd(@NonNull Context context, @NonNull AdSource adSource,
@NonNull String adUnitId, @NonNull SuperCallback callback) {
// Load interstitial ad
}
@Override
public void loadRewardedInterstitialAd(@NonNull Context context, @NonNull AdSource adSource,
@NonNull String adUnitId,
@NonNull SuperCallback callback) {
// Load rewarded interstitial ads
}
}
```
**Ad Type:**
| AdType | Description |
|--------|------|
| `NATIVE` | Native Ads |
| `REWARD` | rewarded video |
| `REWARD_INTERSTITIAL` | Rewarded interstitial ad |
| `INTERSTITIAL` | App Open Ad |
| `BANNER` | Banner Ad |
| `SPLASH` | Splash ad, native entry `loadSplashAd` |
**Ad Source:**
| AdSource | Description |
|----------|------|
| `ADMOB` | Google AdMob |
| `APPLOVIN` | AppLovin |
| `GDT` | Tencent GDT |
| `CSJ` | Domestic CSJ |
> App open ads and the Tencent GDT and CSJ adapters first shipped in **`3.0.8-SNAPSHOT`**. Select that version or a later release that includes them.
#### app open ad
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 `` element and declare `xmlns:tools="http://schemas.android.com/tools"` in the `` element, so that the merged result adopts the host app's value.
#### Integrate Tencent GDT (CSJ)
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()`.
```java
import com.supersdk.ad.gdt.GdtAdService;
// host app field
private volatile AdService adService;
// Execute within the host app's privacy consent callback.
void initializeGdt(Context context, String gdtAppId) {
GdtAdService.initialize(context, gdtAppId, result -> {
if (result.isSuccess()) {
adService = result.getData();
}
});
}
```
| ad placement | Load entry | Display Method |
|--------|----------|----------|
| Banner | `loadBannerAd(activity, AdSource.GDT, bannerId, callback)` | Add `getView()` to the page, and call `destroy()` when exiting or replacing. |
| rewarded video | `loadRewardedAd(context, AdSource.GDT, rewardId, callback)` | Call `show(activity, listener)` to award rewards in `onRewarded()`. |
| App Open Ad | `loadSplashAd(context, AdSource.GDT, splashId, 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.
#### CSJ Integration
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](https://www.csjplatform.com/supportcenter/5397)
```kotlin
dependencyResolutionManagement {
repositories {
google()
mavenCentral()
maven("https://artifact.bytedance.com/repository/pangle") {
content { includeGroup("com.pangle.cn") }
}
}
}
```
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](https://www.csjplatform.com/supportcenter/5405)
```java
import com.supersdk.ad.csj.CsjAdService;
// Execute within the host app's privacy consent callback.
CsjAdService.initialize(context, csjAppId, appName, result -> {
if (result.isSuccess()) {
CsjAdService csj = result.getData();
csj.setBannerSize(bannerId, templateWidth, templateHeight);
adService = csj;
}
});
```
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](https://www.csjplatform.com/supportcenter/5398) · [Rewarded Video](https://www.csjdeveloper.com/supportcenter/5399)
#### AdMob integration example
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 `` 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`.
1. Integrate Provider (minSdk ≥ 23, compileSdk ≥ 35):
```groovy
implementation 'com.supersdk:supersdk-ad-admob:VERSION'
```
2. Declare the AdMob App ID within the `` tag in `AndroidManifest.xml` (**failure to do so will cause the app to crash**):
```xml
```
> 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:
```groovy
android {
defaultConfig {
manifestPlaceholders.ADMOB_APP_ID = 'ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy'
}
}
```
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.
3. 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:
```java
AdMobAdService.initialize(getApplicationContext(), result -> {
if (!result.isSuccess()) {
Log.e("MyApp", "AdMob init failed: " + result.getCode()
+ " " + result.getMessage());
return;
}
AdService adService = new AdMobAdService();
// AdMob App ID configured independently; here, the SuperSDK spid issued by the console is used.
SuperSDK.init(getApplicationContext(), "ab12cd34", new SuperSDKProvider() {
@Override
public AdService getAdService() {
return adService;
}
});
});
```
`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) |
| Android H5 / JSBridge | Rewarded, Rewarded Interstitial, Interstitial, Banner (four 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.
**Google Console** ([AdMob Console](https://apps.admob.com)):
| Steps | Description |
|------|------|
| Register Application | 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](https://developers.google.com/admob/android/test-ads) during development to avoid account suspension due to invalid traffic. |
> Reference: [AdMob Android Quick Start](https://developers.google.com/admob/android/quick-start)
---
### HostNetworkExtensionService - Network Request Extension (Optional)
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.
```java
public class MyProvider implements SuperSDKProvider {
@Override
public HostNetworkExtensionService getHostNetworkExtensionService() {
return new HostNetworkExtensionService() {
@Override
public Map getExtraQueryParams(SuperRequestContext context) {
// Enable response obfuscation: The SDK does not append this parameter by default.
return Collections.singletonMap("suenc", "1");
}
@Override
public Map getExtraHeaders(SuperRequestContext context) {
return Collections.singletonMap("X-Host-Trace", traceId());
}
};
}
}
```
`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):**
> 1. **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.
> 2. `Authorization`, `Cookie`, and other authentication credential headers are **not accepted** for injection via this interface.
> 3. 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.
> 4. All thrown exceptions are caught and **do not block the SDK's main flow**.
> 5. **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.
> 6. Two methods are **synchronously invoked** on the thread that initiates the request; the implementation must return quickly and must not block.
> 7. Download-type requests (offline packages, `downloadFile`) and direct payment receipt delivery **do not inject query parameters**, but header extensions still apply.
### Response obfuscation (suenc)
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:
```java
// Query the locally supported codecs and decide whether to send suenc=1
JSONObject capabilities = SuperSDK.getSuEncCapabilities(); // {"supported":true,"codecs":["b64t1"]}
// The codec must directly use the original value of the X-Su-Enc header from the response; custom encoding tables are not accepted.
try {
String json = SuperSDK.decodeSuEnc(encodedBody, codec);
} catch (SuEncException e) {
// UNSUPPORTED_SUENC_CODEC / SUENC_DECODE_FAILED / SUENC_INVALID_UTF8
String errorCode = e.getErrorCode();
}
```
> **Important Notes:**
> 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.
> 2. 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`.
> 3. 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.
---
## Optional capability module integration
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.)
### Google Sign-In (supersdk-auth-google)
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.
**① Dependencies** (minSdk ≥ 23):
```groovy
implementation 'com.supersdk:supersdk-auth-google:VERSION'
```
**② Register Provider** — Mount `GoogleAuthProvider` in `LoginService`:
```java
private final LoginService loginService = new SDKLoginService.Builder()
.addProvider(new GoogleAuthProvider(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.
**③ Google Console** ([Google Cloud Console → APIs & Services → Credentials](https://console.cloud.google.com/apis/credentials)):
| Steps | Description |
|------|------|
| Configure OAuth consent screen | 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 `).
> Reference: [Sign in with Google (Credential Manager)](https://developer.android.com/identity/sign-in/credential-manager-siwg) · [Backend ID Token Validation](https://developers.google.com/identity/sign-in/android/backend-auth)
### Google Pay In-App Purchase (supersdk-pay-google)
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"`).
**① Dependencies** (minSdk ≥ 23):
```groovy
implementation 'com.supersdk:supersdk-pay-google:1.0.0.67-SNAPSHOT'
```
**② Register Provider** — Mount `GooglePayProvider` in `PayService`:
```java
private final PayService payService = new SDKPayService.Builder()
.addProvider(new GooglePayProvider(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**:
```javascript
const offers = await SuperSDK.pay.querySubscriptionOffers({
provider: 'google_play',
productIds: ['matrixvplan01']
});
const selected = offers[0];
const result = await SuperSDK.pay.purchase({
provider: 'google_play',
payParams: {
productId: selected.productId,
productType: 'subs',
basePlanId: selected.basePlanId,
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.
**④ Google Backend** ([Google Play Console](https://play.google.com/console)):
| Steps | Description |
|------|------|
| Upload App | 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". |
> Reference: [Play Billing Overview](https://developer.android.com/google/play/billing) · [Create Products](https://support.google.com/googleplay/android-developer/answer/1153481) · [Configure RTDN](https://developer.android.com/google/play/billing/getting-ready#configure-rtdn) · [Test Purchases](https://developer.android.com/google/play/billing/test)
### Push (supersdk-push-firebase)
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](https://www.superplatform.ai/en/superpush.md).
**① Dependencies** (minSdk ≥ 23, matching the version of `com.supersdk:supersdk`):
```kotlin
// root build.gradle.kts
plugins { id("com.google.gms.google-services") version "4.4.2" apply false }
// app/build.gradle.kts
plugins { id("com.google.gms.google-services") }
dependencies { implementation("com.supersdk:supersdk-push-firebase:VERSION") }
```
- 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):
```java
private final PushService pushService = new SDKPushService.Builder()
.addProvider(new FirebasePushProvider(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`):
```java
PushService push = SuperSDK.getPushService();
push.requestPermission(activity, result -> { // Android 13+ displays the system notification permission dialog; <13 directly returns the current status.
PushPermissionStatus p = result.getData(); // GRANTED / DENIED / PROMPT
});
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
push.setUserId("u_12345"); // ≤128 characters; null / empty string = clear; clear on logout
push.setListener(new PushListener() {
@Override public boolean onMessage(PushMessage m) { return false; } // Front-end receives: true = self-displayed; SDK does not trigger system notifications.
@Override public boolean onOpened(PushMessage m) { return false; } // User clicks; true = full takeover, SDK will no longer open the URL
});
PushStatus status = push.getStatus(); // supported / permission / registered / lastError
```
- 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 version** `implementation("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 ` log per process in logcat):
```xml
```
```java
@Override public void onNewToken(String token) { FirebasePushProvider.handleNewToken(token); }
@Override public void onMessageReceived(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 `, 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.
**⑨ Firebase Console** ([Firebase Console](https://console.firebase.google.com)):
| Steps | Description |
|------|------|
| Add Android app | 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`. |
> Reference: [FCM Android Client Setup](https://firebase.google.com/docs/cloud-messaging/android/client) · [Android 13 Notification Runtime Permission](https://developer.android.com/develop/ui/views/notifications/notification-permission)
---
## General Callback Mode
The SDK uses the `SuperCallback` + `SuperResult` pattern for asynchronous callbacks.
```java
SuperSDK.someAsyncMethod(new SuperCallback() {
@Override
public void onResult(@NonNull SuperResult result) {
if (result.isSuccess()) {
SomeData data = result.getData();
// Success
} else {
String code = result.getCode();
String message = result.getMessage();
// Processing failed
}
}
});
```
**SuperResult Error Codes:**
| Code | Description |
|------|------|
| `SUCCESS` | Success |
| `FAIL_UNKNOWN` | Unknown error |
| `FAIL_TIMEOUT` | timeout |
---
## Complete integration example
```java
// 1. Application Initialization
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
SuperSDK.init(this, "ab12cd34", new MySDKProvider());
}
}
// 2. Use in Activity
public class WebActivity extends AppCompatActivity {
private AbsSuperPageView pageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
FrameLayout container = findViewById(R.id.web_container);
// Create PageView
pageView = SuperSDK.getPageController().createPageView();
container.addView(pageView);
// Adapt to immersive safe area
pageView.fitSystemWindows(this);
// Set up page close listener (triggered when the frontend calls `closePage`).
pageView.setOnClosePageListener(this::finish);
// Load URL
String url = "https://example.com";
pageView.load(url, new PageLoadConfig(url));
}
@Override
protected void onDestroy() {
super.onDestroy();
if (pageView != null) {
pageView.destroyView();
}
}
@Override
public void onBackPressed() {
// Priority: Frontend interception > Page history back > Close Activity
if (pageView != null) {
pageView.handleBackPressed(() -> super.onBackPressed());
} else {
super.onBackPressed();
}
}
}
```
---
## Proguard configuration
If the project enables ProGuard/R8 obfuscation, please add the following rules:
```proguard
-keep class com.supersdk.** { *; }
-keep class * implements com.supersdk.api.SuperSDKProvider { *; }
```
---
## Notes
1. **Initialization Timing**: `SuperSDK.init()` must be called before using any SDK features; it is recommended to call it within `Application.onCreate()`.
2. **Lifecycle**: The SDK automatically perceives the Activity lifecycle via `onWindowVisibilityChanged` internally, without requiring manual dispatching.
3. **Back Key Handling**: Use `handleBackPressed(exitAction)` to handle the back key; the SDK automatically manages frontend interception and page history back navigation.
4. **Destroy**: When an Activity is destroyed, you must call `pageView.destroyView()` to release resources.
5. **Thread Safety**: SDK UI operations are automatically switched to the main thread; the host app requires no additional handling.
6. **Offline package**: The SDK supports built-in offline packages, automatically matching local resources when loading a URL.