Android: native ads with small and medium templates

- loadNativeAd / showNativeAd / setNativeAdRect / hideNativeAd / destroyNativeAd; one LevelPlayNativeAd per load
  and slot, the previous ad of the slot is destroyed first.
- Templates built in code in a NativeAdLayout: icon, title, Ad badge, advertiser, body, CTA button and (medium)
  LevelPlayMediaView, registered with registerNativeAdViews; bottom-left corner left free for AdChoices.
- Style: background / title / body / CTA colours, corner radius, font family (system name or a .ttf / .otf in the
  web assets) and size for title, body and CTA. Badge and CTA fallback texts are overridable string resources.
- nativeAd* events; native impressions also emit impressionData (adFormat nativead).
This commit is contained in:
CRTkafa 2026-10-10 03:35:31 +08:00
parent 4cf95e286d
commit 1e0be782da
5 changed files with 705 additions and 0 deletions

View file

@ -479,6 +479,84 @@ public class LevelPlayPlugin extends Plugin {
}); });
} }
// ---------------------------------------------------------------------------------------------- 0.3.0: native ads
private final NativeAdManager nativeAds = new NativeAdManager(new NativeAdManager.Host() {
@Nullable
@Override
public Activity activity() {
return getActivity();
}
@Nullable
@Override
public OverlayHost overlay() {
return LevelPlayPlugin.this.overlay();
}
@Override
public boolean initialized() {
return initState == InitState.DONE;
}
@Override
public void emit(String event, JSObject data) {
notifyListeners(event, data);
}
@Override
public void impression(JSObject data) {
emitImpression(data);
}
});
@PluginMethod
public void loadNativeAd(PluginCall call) {
JSObject o = call.getData();
onMain(call, () -> {
nativeAds.load(o);
call.resolve();
});
}
@PluginMethod
public void showNativeAd(PluginCall call) {
String id = call.getString("nativeAdId");
JSObject rect = call.getObject("rect");
onMain(call, () -> {
nativeAds.show(id, rect);
call.resolve();
});
}
@PluginMethod
public void setNativeAdRect(PluginCall call) {
String id = call.getString("nativeAdId");
JSObject rect = call.getObject("rect");
onMain(call, () -> {
nativeAds.setRect(id, rect);
call.resolve();
});
}
@PluginMethod
public void hideNativeAd(PluginCall call) {
String id = call.getString("nativeAdId");
onMain(call, () -> {
nativeAds.hide(id);
call.resolve();
});
}
@PluginMethod
public void destroyNativeAd(PluginCall call) {
String id = call.getString("nativeAdId");
onMain(call, () -> {
nativeAds.destroy(id);
call.resolve();
});
}
// ---------------------------------------------------------------------------------------------- overlay, lifecycle // ---------------------------------------------------------------------------------------------- overlay, lifecycle
/** Main thread. The pass-through overlay above the WebView, attached on first use (design §6.2). */ /** Main thread. The pass-through overlay above the WebView, attached on first use (design §6.2). */
@ -491,6 +569,7 @@ public class LevelPlayPlugin extends Plugin {
private void onOverlayLayoutChanged() { private void onOverlayLayoutChanged() {
if (overlay == null) return; if (overlay == null) return;
banners.onLayoutChanged(overlay); banners.onLayoutChanged(overlay);
nativeAds.onLayoutChanged(overlay);
} }
@Override @Override
@ -506,6 +585,7 @@ public class LevelPlayPlugin extends Plugin {
super.handleOnDestroy(); super.handleOnDestroy();
Runnable cleanup = () -> { Runnable cleanup = () -> {
banners.destroyAll(); banners.destroyAll();
nativeAds.destroyAll();
if (overlay != null) { if (overlay != null) {
overlay.detach(); overlay.detach();
overlay = null; overlay = null;

View file

@ -0,0 +1,254 @@
package fyi.crt.capacitor.levelplay;
import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.getcapacitor.JSObject;
import com.ironsource.mediationsdk.ads.nativead.LevelPlayNativeAd;
import com.ironsource.mediationsdk.ads.nativead.LevelPlayNativeAdListener;
import com.ironsource.mediationsdk.ads.nativead.NativeAdLayout;
import com.ironsource.mediationsdk.adunit.adapter.utility.AdInfo;
import com.ironsource.mediationsdk.logger.IronSourceError;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Native ads (design §4): one LevelPlayNativeAd per load and slot, rendered into the plugin's templates and placed in
* the OverlayHost at a WebView-local CSS rect. Main thread only; SDK callbacks are re-posted to the main thread.
*/
final class NativeAdManager {
interface Host {
@Nullable
Activity activity();
@Nullable
OverlayHost overlay();
boolean initialized();
void emit(String event, JSObject data);
/** impressionData synthesised from the native ad info (no per-ad impression listener for native ads). */
void impression(JSObject data);
}
private final Host host;
private final Handler main = new Handler(Looper.getMainLooper());
private final Map<String, Slot> slots = new LinkedHashMap<>();
NativeAdManager(Host host) {
this.host = host;
}
private static final class Slot {
final String id;
@Nullable
final String placementName;
final String template;
final NativeAdStyle style;
@Nullable
LevelPlayNativeAd ad;
boolean loaded;
@Nullable
NativeAdLayout view;
@Nullable
double[] rect;
boolean visible;
Slot(String id, @Nullable String placementName, String template, NativeAdStyle style) {
this.id = id;
this.placementName = placementName;
this.template = template;
this.style = style;
}
}
// ---------------------------------------------------------------------------------------------- API
void load(JSObject o) throws CallError {
String id = requireId(o.getString("nativeAdId"));
String template = o.getString("template", "medium");
if (!"small".equals(template) && !"medium".equals(template)) {
throw new CallError("UNSUPPORTED", "Template '" + template + "' is not supported (small, medium)");
}
NativeAdStyle style = NativeAdStyle.parse(o.getJSObject("style"));
String placement = o.getString("placementName");
if (placement != null && placement.isEmpty()) placement = null;
if (!host.initialized()) throw new CallError("NOT_INITIALIZED", "Call initialize() and wait for it before loadNativeAd()");
Activity activity = host.activity();
if (activity == null) throw new CallError("NO_ACTIVITY", "No activity to load the native ad with");
// "Destroy the ad object and create a new one for every new load" (Unity).
Slot old = slots.remove(id);
if (old != null) destroySlot(old);
Slot s = new Slot(id, placement, template, style);
LevelPlayNativeAd.Builder b = new LevelPlayNativeAd.Builder().withActivity(activity).withListener(new Listener(s));
if (placement != null) b.withPlacementName(placement);
s.ad = b.build();
slots.put(id, s);
s.ad.loadAd();
}
void show(String nativeAdId, @Nullable JSObject rect) throws CallError {
Slot s = require(nativeAdId);
double[] r = parseRect(rect);
if (!s.loaded || s.ad == null) throw new CallError("NOT_LOADED", "Native ad '" + nativeAdId + "' is not loaded");
OverlayHost overlay = host.overlay();
Activity activity = host.activity();
if (overlay == null || activity == null) throw new CallError("NO_ACTIVITY", "No activity / WebView to show the native ad in");
if (s.view == null) {
s.view = NativeAdTemplate.build(activity, s.template, s.style, s.ad);
s.view.setVisibility(View.GONE);
overlay.add(s.view);
}
s.rect = r;
s.visible = true;
place(s, overlay);
s.view.setVisibility(View.VISIBLE);
s.view.bringToFront();
}
void setRect(String nativeAdId, @Nullable JSObject rect) throws CallError {
Slot s = require(nativeAdId);
s.rect = parseRect(rect);
OverlayHost overlay = host.overlay();
if (overlay != null && s.view != null) place(s, overlay);
}
void hide(String nativeAdId) throws CallError {
Slot s = require(nativeAdId);
s.visible = false;
if (s.view != null) s.view.setVisibility(View.GONE);
}
void destroy(@Nullable String nativeAdId) {
if (nativeAdId == null) return;
Slot s = slots.remove(nativeAdId);
if (s != null) destroySlot(s);
}
void destroyAll() {
for (Slot s : new ArrayList<>(slots.values())) destroySlot(s);
slots.clear();
}
void onLayoutChanged(OverlayHost overlay) {
for (Slot s : slots.values()) if (s.view != null && s.rect != null) place(s, overlay);
}
// ---------------------------------------------------------------------------------------------- internals
private static String requireId(@Nullable String id) throws CallError {
if (id == null || id.isEmpty()) throw CallError.invalid("nativeAdId is required");
return id;
}
private Slot require(@Nullable String id) throws CallError {
Slot s = slots.get(requireId(id));
if (s == null) throw CallError.notFound("Native ad", id);
return s;
}
private static double[] parseRect(@Nullable JSObject r) throws CallError {
if (r == null) throw CallError.invalid("rect { x, y, width, height } is required");
double[] out = new double[4];
String[] keys = { "x", "y", "width", "height" };
for (int i = 0; i < 4; i++) {
Object v = r.opt(keys[i]);
if (!(v instanceof Number)) throw CallError.invalid("rect." + keys[i] + " must be a number");
double d = ((Number) v).doubleValue();
if (Double.isNaN(d) || Double.isInfinite(d)) throw CallError.invalid("rect." + keys[i] + " must be finite");
out[i] = d;
}
if (out[2] < 0 || out[3] < 0) throw CallError.invalid("rect width and height must be >= 0");
return out;
}
/** Native rects are taken literally (the page laid them out), only clamped to the WebView (design §6.3). */
private static void place(Slot s, OverlayHost overlay) {
if (s.view == null || s.rect == null) return;
overlay.place(s.view, OverlayMath.intersect(s.rect, overlay.webViewCss()));
}
private void destroySlot(Slot s) {
if (s.view != null) {
OverlayHost overlay = host.overlay();
if (overlay != null) overlay.remove(s.view);
s.view = null;
}
if (s.ad != null) {
s.ad.destroyAd();
s.ad = null;
}
s.loaded = false;
}
private JSObject event(Slot s, @Nullable AdInfo info) {
JSObject o = new JSObject();
o.put("nativeAdId", s.id);
if (s.placementName != null) o.put("placementName", s.placementName);
if (info != null) o.put("adInfo", Mappers.nativeAdInfo(info));
return o;
}
/** One listener per load; callbacks of an ad object that was replaced or destroyed are dropped. */
private final class Listener implements LevelPlayNativeAdListener {
private final Slot slot;
Listener(Slot slot) {
this.slot = slot;
}
private boolean current(@Nullable LevelPlayNativeAd ad) {
return slots.get(slot.id) == slot && slot.ad != null && slot.ad == ad;
}
@Override
public void onAdLoaded(@NonNull LevelPlayNativeAd ad, @NonNull AdInfo adInfo) {
main.post(() -> {
if (!current(ad)) return;
slot.loaded = true;
host.emit("nativeAdLoaded", event(slot, adInfo));
});
}
@Override
public void onAdLoadFailed(@NonNull LevelPlayNativeAd ad, @NonNull IronSourceError error) {
main.post(() -> {
if (!current(ad)) return;
// The failed ad object is destroyed; the slot stays (NOT_LOADED) until the next loadNativeAd().
slot.ad.destroyAd();
slot.ad = null;
slot.loaded = false;
JSObject o = event(slot, null);
o.put("error", Mappers.error(error.getErrorCode(), error.getErrorMessage()));
host.emit("nativeAdLoadFailed", o);
});
}
@Override
public void onAdImpression(@NonNull LevelPlayNativeAd ad, @NonNull AdInfo adInfo) {
main.post(() -> {
if (!current(ad)) return;
host.emit("nativeAdImpression", event(slot, adInfo));
host.impression(Mappers.nativeImpression(adInfo));
});
}
@Override
public void onAdClicked(@NonNull LevelPlayNativeAd ad, @NonNull AdInfo adInfo) {
main.post(() -> {
if (!current(ad)) return;
host.emit("nativeAdClicked", event(slot, adInfo));
});
}
}
}

View file

@ -0,0 +1,75 @@
package fyi.crt.capacitor.levelplay;
import androidx.annotation.Nullable;
import com.getcapacitor.JSObject;
/** Parsed NativeAdTemplateStyle (src/definitions.ts). Colours are ARGB; sizes are CSS px (dp). */
final class NativeAdStyle {
static final class Font {
@Nullable
final String family;
@Nullable
final Double size;
Font(@Nullable String family, @Nullable Double size) {
this.family = family;
this.size = size;
}
}
int backgroundColor = 0xFFFFFFFF;
int titleColor = 0xFF202124;
int bodyColor = 0xFF5F6368;
int callToActionBackgroundColor = 0xFF1A73E8;
int callToActionTextColor = 0xFFFFFFFF;
double cornerRadius = 0;
Font titleFont = new Font(null, null);
Font bodyFont = new Font(null, null);
Font callToActionFont = new Font(null, null);
static NativeAdStyle parse(@Nullable JSObject o) throws CallError {
NativeAdStyle s = new NativeAdStyle();
if (o == null) return s;
s.backgroundColor = color(o, "backgroundColor", s.backgroundColor);
s.titleColor = color(o, "titleColor", s.titleColor);
s.bodyColor = color(o, "bodyColor", s.bodyColor);
s.callToActionBackgroundColor = color(o, "callToActionBackgroundColor", s.callToActionBackgroundColor);
s.callToActionTextColor = color(o, "callToActionTextColor", s.callToActionTextColor);
if (o.has("cornerRadius") && !o.isNull("cornerRadius")) {
Object v = o.opt("cornerRadius");
if (!(v instanceof Number) || !(((Number) v).doubleValue() >= 0)) throw CallError.invalid("style.cornerRadius must be >= 0");
s.cornerRadius = ((Number) v).doubleValue();
}
s.titleFont = font(o, "titleFont");
s.bodyFont = font(o, "bodyFont");
s.callToActionFont = font(o, "callToActionFont");
return s;
}
private static int color(JSObject o, String key, int fallback) throws CallError {
if (!o.has(key) || o.isNull(key)) return fallback;
Integer c = OverlayMath.parseColor(o.optString(key, null));
if (c == null) throw CallError.invalid("style." + key + " must be #RRGGBB or #RRGGBBAA");
return c;
}
private static Font font(JSObject o, String key) throws CallError {
if (!o.has(key) || o.isNull(key)) return new Font(null, null);
JSObject f = o.getJSObject(key);
if (f == null) throw CallError.invalid("style." + key + " must be an object { family?, size? }");
String family = f.getString("family");
if (family != null && family.trim().isEmpty()) family = null;
Double size = null;
if (f.has("size") && !f.isNull("size")) {
Object v = f.opt("size");
if (!(v instanceof Number) || !(((Number) v).doubleValue() > 0) || Double.isInfinite(((Number) v).doubleValue())) {
throw CallError.invalid("style." + key + ".size must be a positive number");
}
size = ((Number) v).doubleValue();
}
return new Font(family, size);
}
}

View file

@ -0,0 +1,290 @@
package fyi.crt.capacitor.levelplay;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
import com.ironsource.mediationsdk.ads.nativead.LevelPlayMediaView;
import com.ironsource.mediationsdk.ads.nativead.LevelPlayNativeAd;
import com.ironsource.mediationsdk.ads.nativead.NativeAdLayout;
import com.ironsource.mediationsdk.ads.nativead.interfaces.NativeAdDataInterface;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* The plugin's own native ad templates (the SDK ships none, design §4.1), built in code so every style value applies
* directly. Both draw an "Ad" badge and keep the bottom-left corner free for the network's privacy / AdChoices icon.
*
* - small: [icon] [title / Ad + advertiser / body] [CTA], one row; fits rows from about 90 px tall.
* - medium: [icon] [title / Ad + advertiser], body, media view (fills the rest), CTA aligned right.
*/
final class NativeAdTemplate {
private static final String TAG = "LevelPlay";
private static final int BADGE_BG = 0xFFFFC107;
private static final int BADGE_TEXT = 0xFF202124;
private static final Map<String, Typeface> ASSET_FONTS = new HashMap<>();
private static final ExecutorService IO = Executors.newSingleThreadExecutor();
private NativeAdTemplate() {}
static NativeAdLayout build(Context ctx, String template, NativeAdStyle style, LevelPlayNativeAd ad) {
boolean medium = "medium".equals(template);
NativeAdLayout root = new NativeAdLayout(ctx);
GradientDrawable bg = new GradientDrawable();
bg.setColor(style.backgroundColor);
bg.setCornerRadius(dp(ctx, style.cornerRadius));
root.setBackground(bg);
root.setClipToOutline(true);
// The template consumes touches inside its bounds so taps between asset views do not reach the game.
root.setClickable(true);
ImageView icon = new ImageView(ctx);
icon.setScaleType(ImageView.ScaleType.CENTER_CROP);
GradientDrawable iconBg = new GradientDrawable();
iconBg.setCornerRadius(dp(ctx, 6));
iconBg.setColor(0x14000000);
icon.setBackground(iconBg);
icon.setClipToOutline(true);
TextView title = text(ctx, style.titleColor, 15, style.titleFont, true);
title.setMaxLines(medium ? 2 : 1);
TextView badge = text(ctx, BADGE_TEXT, 10, style.bodyFont, true);
badge.setText(R.string.levelplay_native_ad_badge);
badge.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 10);
GradientDrawable badgeBg = new GradientDrawable();
badgeBg.setColor(BADGE_BG);
badgeBg.setCornerRadius(dp(ctx, 3));
badge.setBackground(badgeBg);
int bp = (int) dp(ctx, 4);
badge.setPadding(bp, 0, bp, 0);
TextView advertiser = text(ctx, style.bodyColor, 12, style.bodyFont, false);
advertiser.setMaxLines(1);
TextView body = text(ctx, style.bodyColor, 12, style.bodyFont, false);
body.setMaxLines(2);
Button cta = new Button(ctx);
cta.setAllCaps(false);
cta.setStateListAnimator(null);
cta.setMinWidth(0);
cta.setMinimumWidth(0);
cta.setMinHeight(0);
cta.setMinimumHeight(0);
cta.setSingleLine(true);
cta.setEllipsize(TextUtils.TruncateAt.END);
cta.setTextColor(style.callToActionTextColor);
applyFont(ctx, cta, style.callToActionFont, 13, true);
GradientDrawable ctaBg = new GradientDrawable();
ctaBg.setColor(style.callToActionBackgroundColor);
ctaBg.setCornerRadius(dp(ctx, 6));
cta.setBackground(ctaBg);
int cp = (int) dp(ctx, 12);
cta.setPadding(cp, 0, cp, 0);
cta.setGravity(Gravity.CENTER);
// Badge + advertiser row.
LinearLayout adRow = new LinearLayout(ctx);
adRow.setOrientation(LinearLayout.HORIZONTAL);
adRow.setGravity(Gravity.CENTER_VERTICAL);
adRow.addView(badge, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
LinearLayout.LayoutParams advLp = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1);
advLp.leftMargin = (int) dp(ctx, 6);
adRow.addView(advertiser, advLp);
LevelPlayMediaView media = null;
int pad = (int) dp(ctx, medium ? 10 : 8);
if (medium) {
LinearLayout col = new LinearLayout(ctx);
col.setOrientation(LinearLayout.VERTICAL);
col.setPadding(pad, pad, pad, pad);
LinearLayout header = new LinearLayout(ctx);
header.setOrientation(LinearLayout.HORIZONTAL);
header.setGravity(Gravity.CENTER_VERTICAL);
int is = (int) dp(ctx, 40);
header.addView(icon, new LinearLayout.LayoutParams(is, is));
LinearLayout texts = new LinearLayout(ctx);
texts.setOrientation(LinearLayout.VERTICAL);
texts.addView(title);
texts.addView(adRow);
LinearLayout.LayoutParams tLp = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1);
tLp.leftMargin = (int) dp(ctx, 8);
header.addView(texts, tLp);
col.addView(header);
LinearLayout.LayoutParams bodyLp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
bodyLp.topMargin = (int) dp(ctx, 6);
col.addView(body, bodyLp);
media = new LevelPlayMediaView(ctx);
LinearLayout.LayoutParams mLp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1);
mLp.topMargin = (int) dp(ctx, 8);
col.addView(media, mLp);
// CTA on the right: the bottom-left corner stays free for the AdChoices icon.
LinearLayout.LayoutParams ctaLp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, (int) dp(ctx, 36));
ctaLp.topMargin = (int) dp(ctx, 8);
ctaLp.gravity = Gravity.END;
col.addView(cta, ctaLp);
root.addView(col, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
} else {
LinearLayout row = new LinearLayout(ctx);
row.setOrientation(LinearLayout.HORIZONTAL);
row.setGravity(Gravity.CENTER_VERTICAL);
row.setPadding(pad, pad, pad, pad);
int is = (int) dp(ctx, 48);
row.addView(icon, new LinearLayout.LayoutParams(is, is));
LinearLayout texts = new LinearLayout(ctx);
texts.setOrientation(LinearLayout.VERTICAL);
texts.addView(title);
texts.addView(adRow);
texts.addView(body);
LinearLayout.LayoutParams tLp = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1);
tLp.leftMargin = (int) dp(ctx, 8);
tLp.rightMargin = (int) dp(ctx, 8);
row.addView(texts, tLp);
row.addView(cta, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, (int) dp(ctx, 36)));
root.addView(row, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
// Assets.
setOrHide(title, ad.getTitle());
setOrHide(advertiser, ad.getAdvertiser());
setOrHide(body, ad.getBody());
String ctaText = ad.getCallToAction();
if (ctaText != null && !ctaText.isEmpty()) cta.setText(ctaText);
else cta.setText(R.string.levelplay_native_ad_cta_fallback);
bindIcon(icon, ad.getIcon());
root.setTitleView(title);
root.setAdvertiserView(advertiser);
root.setBodyView(body);
root.setIconView(icon);
root.setCallToActionView(cta);
if (media != null) root.setMediaView(media);
root.registerNativeAdViews(ad);
return root;
}
private static TextView text(Context ctx, int color, double defaultSize, NativeAdStyle.Font font, boolean bold) {
TextView t = new TextView(ctx);
t.setTextColor(color);
t.setEllipsize(TextUtils.TruncateAt.END);
t.setIncludeFontPadding(false);
applyFont(ctx, t, font, defaultSize, bold);
return t;
}
private static void applyFont(Context ctx, TextView t, NativeAdStyle.Font font, double defaultSize, boolean bold) {
// CSS px = dp, and like WebView text it ignores the system font scale.
t.setTextSize(TypedValue.COMPLEX_UNIT_DIP, (float) (font.size != null ? font.size : defaultSize));
Typeface tf = typeface(ctx, font.family, bold);
t.setTypeface(tf);
}
/** System family name, or a .ttf / .otf file in the web assets (Capacitor copies the web dir to assets/public). */
static Typeface typeface(Context ctx, @Nullable String family, boolean bold) {
int style = bold ? Typeface.BOLD : Typeface.NORMAL;
if (family == null) return Typeface.defaultFromStyle(style);
String lower = family.toLowerCase(java.util.Locale.ROOT);
if (lower.endsWith(".ttf") || lower.endsWith(".otf")) {
String path = family;
while (path.startsWith("/")) path = path.substring(1);
if (path.startsWith("./")) path = path.substring(2);
String asset = "public/" + path;
synchronized (ASSET_FONTS) {
Typeface cached = ASSET_FONTS.get(asset);
if (cached != null) return cached;
try {
Typeface tf = Typeface.createFromAsset(ctx.getAssets(), asset);
ASSET_FONTS.put(asset, tf);
return tf;
} catch (RuntimeException e) {
Log.w(TAG, "Native ad font not found in assets: " + asset + "; using the system font");
return Typeface.defaultFromStyle(style);
}
}
}
return Typeface.create(family, style);
}
private static void setOrHide(TextView v, @Nullable String text) {
if (text == null || text.trim().isEmpty()) {
v.setText("");
v.setVisibility(View.GONE);
} else {
v.setText(text);
v.setVisibility(View.VISIBLE);
}
}
private static void bindIcon(ImageView icon, @Nullable NativeAdDataInterface.Image image) {
if (image == null) {
icon.setVisibility(View.GONE);
return;
}
Drawable d = image.getDrawable();
if (d != null) {
icon.setImageDrawable(d);
return;
}
Uri uri = image.getUri();
if (uri == null || uri.getScheme() == null || !uri.getScheme().startsWith("http")) {
icon.setVisibility(View.GONE);
return;
}
// Some adapters only give a URL: fetch it off the main thread.
Handler main = new Handler(Looper.getMainLooper());
String url = uri.toString();
IO.execute(() -> {
Bitmap bmp = null;
HttpURLConnection c = null;
try {
c = (HttpURLConnection) new URL(url).openConnection();
c.setConnectTimeout(10000);
c.setReadTimeout(10000);
try (InputStream in = c.getInputStream()) {
bmp = BitmapFactory.decodeStream(in);
}
} catch (Exception e) {
Log.w(TAG, "Native ad icon download failed: " + e);
} finally {
if (c != null) c.disconnect();
}
Bitmap result = bmp;
main.post(() -> {
if (result != null) icon.setImageBitmap(result);
else icon.setVisibility(View.GONE);
});
});
}
static float dp(Context ctx, double v) {
return (float) (v * ctx.getResources().getDisplayMetrics().density);
}
}

View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Native ad template texts. Apps can translate or replace them by defining the same names in their own res. -->
<string name="levelplay_native_ad_badge">Ad</string>
<string name="levelplay_native_ad_cta_fallback">Open</string>
</resources>