Skip to content

一、简介

该章节主要介绍如何在 Android 项目的 WebView 中集成 H5 广告:

二、集成

前提条件

  • unad_global SDK 版本在 2.8.1 及以上版本
  • 如需使用 CustomTabsIntent 优化点击跳转行为,请添加以下依赖:
groovy
dependencies {
  implementation 'androidx.browser:browser:1.5.0'
}

1、设置 WebView

调用 UNADWebViewAds.register 方法来注册 WebView。

java
public class WebViewAdsActivity extends Activity {


    private static final String TEST_URL = "https://adgo.top/test/webview.html";
    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview_ads);

        webView = findViewById(R.id.webview_ads);
        UNADWebViewAds.register(webView);
        webView.setWebViewClient(new CustomerWebViewClient());
        webView.loadUrl(TEST_URL);
    }
}

2、优化点击行为

开发者需要根据自己的 H5 业务域名自行判断点击后的打开方式:需要继续在 WebView 中展示的域名返回 false,其他外部域名建议使用 CustomTabsIntent 或系统浏览器打开。

下面的 CustomerWebViewClient 是上面 webView.setWebViewClient(new CustomerWebViewClient()) 设置的自定义 WebViewClient,用于接管 WebView 内链接点击后的跳转逻辑。

java
private class CustomerWebViewClient extends WebViewClient {
      @Override
      public boolean shouldOverrideUrlLoading(
              WebView view,
              WebResourceRequest request) {
          Uri uri = request.getUrl();
          String scheme = uri.getScheme();
          String targetDomain = uri.getHost();

          if (scheme == null || targetDomain == null) {
              return false;
          }

          // 处理非 http/https 协议
          if (!scheme.equals("http") && !scheme.equals("https")) {
              Intent intent = new Intent(Intent.ACTION_VIEW, uri);
              try {
                  WebViewAdsActivity.this.startActivity(intent);
              } catch (ActivityNotFoundException exception) {
                  Log.d(TAG, "Failed to load URL with scheme:" + scheme);
              }
              return true;
          }

          // 如果是目标域名,在 WebView 内打开
          if (isTargetDomain(targetDomain)) {
             return false;
          }

          // 其他域名使用 CustomTabsIntent 打开
          CustomTabsIntent intent = new CustomTabsIntent.Builder().build();
          intent.launchUrl(WebViewAdsActivity.this, uri);
          return true;
      }

      /**
       * TODO 检查是否为目标域名(在 WebView 内打开)
       */
      private boolean isTargetDomain(String domain) {
          if (domain == null) {
              return false;
          }
          // TODO 此处修改为需要在 WebView 中展示的 H5 网站域名
          return domain.endsWith(".adgo.top") || domain.endsWith(".example.com");
      }
}