最佳化自訂分頁

廣告專用的網頁瀏覽 API 可讓 CustomTabSession 中的代碼使用應用程式信號,協助提供內容的網站發布商提升營利,並保護廣告主免受垃圾內容干擾。

運作方式

只有在回應下列任一項目觸發的廣告事件時,才會與 GMA Next-Gen SDK 通訊:

GMA Next-Gen SDK 會運用 Android 架構提供的 CustomTabsSession,開啟 postMessage 管道,以利通訊。

必要條件

將應用程式 ID 傳遞至 SDK

如果您已有 Ad Manager 應用程式 ID,請使用現有的應用程式 ID 初始化 GMA Next-Gen SDK

如果沒有 Ad Manager 應用程式 ID,請在初始化 GMA 新一代 SDK 時,傳遞 InitializationConfig.WEBVIEW_APIS_FOR_ADS_APPLICATION_ID 做為應用程式 ID:

Kotlin

MobileAds.initialize(
    this@MainActivity,
    // Use this application ID to initialize the GMA Next-Gen SDK if
    // you don't have an Ad Manager application ID.
    InitializationConfig.Builder(InitializationConfig.WEBVIEW_APIS_FOR_ADS_APPLICATION_ID)
        .build(),
  ) {
    // Adapter initialization complete.
  }

Java

MobileAds.initialize(
    this,
    // Use this application ID to initialize the GMA Next-Gen SDK if
    // you don't have an Ad Manager application ID.
    new InitializationConfig.Builder(InitializationConfig.WEBVIEW_APIS_FOR_ADS_APPLICATION_ID)
        .build(),
        initializationStatus -> {
          // Adapter initialization is complete.
          });

導入作業

在導入 Chrome 自訂分頁時,修改 onCustomTabsServiceConnected() 回呼中的程式碼。將 newSession() 替換為 MobileAds.registerCustomTabsSession(),這會建立與 postMessage 管道的連線,進而使用 SDK 信號擴充廣告代碼。如要連結 postMessage 管道,須使用 Digital Asset Links。您也可以設定 CustomTabsCallback 參數,監聽 Chrome 自訂分頁事件。

您應仍可透過自 GMA Next-Gen SDK 接收的 CustomTabsSession 傳送訊息,但 SDK 要求新管道來覆寫現有管道時,通訊埠可能會變更。

下列程式碼片段說明如何使用 GMA Next-Gen SDK 註冊 CustomTabsSession

Kotlin

import com.google.android.libraries.ads.mobile.sdk.MobileAds

class MainActivity : ComponentActivity() {
  private var customTabsClient: CustomTabsClient? = null
  private var customTabsSession: CustomTabsSession? = null

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    // Get the default browser package name, this will be null if
    // the default browser does not provide a CustomTabsService.
    val packageName = CustomTabsClient.getPackageName(applicationContext, null);
    if (packageName == null) {
      // Do nothing as service connection is not supported.
      return
    }

    CustomTabsClient.bindCustomTabsService(
      applicationContext,
      packageName,
      object : CustomTabsServiceConnection() {
        override fun onCustomTabsServiceConnected(
          name: ComponentName, client: CustomTabsClient,
          ) {
            customTabsClient = client

            // Warm up the browser process.
            customTabsClient?.warmup(0L)
            // Create a new browser session using the GMA Next-Gen SDK.
            customTabsSession = MobileAds.INSTANCE.registerCustomTabsSession(
              client,
              // Checks the "Digital Asset Link" to connect the postMessage channel.
              ORIGIN,
              // Optional parameter to receive the delegated callbacks.
              customTabsCallback
            )

            // Create a new browser session if the GMA Next-Gen SDK is
            // unable to create one.
            if (customTabsSession == null) {
              customTabsSession = client.newSession(customTabsCallback)
            }

            // Pass the custom tabs session into the intent.
            val customTabsIntent = CustomTabsIntent.Builder(customTabsSession).build()
            customTabsIntent.launchUrl(this@MainActivity,
                                      Uri.parse("YOUR_URL"))
          }

          override fun onServiceDisconnected(componentName: ComponentName) {
            // Remove the custom tabs client and custom tabs session.
            customTabsClient = null
            customTabsSession = null
          }
      })
  }

  // Listen for events from the CustomTabsSession delegated by the GMA Next-Gen SDK.
  private val customTabsCallback: CustomTabsCallback = object : CustomTabsCallback() {
    @Synchronized
    override fun onNavigationEvent(navigationEvent: Int, extras: Bundle?) {
      // Called when a navigation event happens.
    }

    @Synchronized
    override fun onMessageChannelReady(extras: Bundle?) {
      // Called when the channel is ready for sending and receiving messages on both
      // ends.
      // This frequently happens, such as each time the SDK requests a
      // new channel.
    }

    @Synchronized
    override fun onPostMessage(message: String, extras: Bundle?) {
      // Called when a tab controlled by this CustomTabsSession has sent a postMessage.
    }

    override fun onRelationshipValidationResult(
      relation: Int, requestedOrigin: Uri, result: Boolean, extras: Bundle?
    ) {
      // Called when a relationship validation result is available.
    }

    override fun onActivityResized(height: Int, width: Int, extras: Bundle) {
      // Called when the tab is resized.
    }

    override fun extraCallback(callbackName: String, args: Bundle?) {

    }

    override fun extraCallbackWithResult(callbackName: String, args: Bundle?): Bundle? {
      return null
    }
  }

  companion object {
    // Replace this URL with an associated website.
    const val ORIGIN = "https://www.google.com"
  }
}

Java

import com.google.android.libraries.ads.mobile.sdk.MobileAds;

class MainActivity extends ComponentActivity {
  // Replace this URL with an associated website.
  private static final String ORIGIN = "https://www.google.com";
  private CustomTabsClient customTabsClient;
  private CustomTabsSession customTabsSession;

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Get the default browser package name, this will be null if
    // the default browser does not provide a CustomTabsService.
    String packageName = CustomTabsClient.getPackageName(getApplicationContext(), null);
    if (packageName == null) {
      // Do nothing as service connection is not supported.
      return;
    }

    CustomTabsClient.bindCustomTabsService(
        getApplicationContext(),
        packageName,
        new CustomTabsServiceConnection() {
          @Override
          public void onCustomTabsServiceConnected(@NonNull ComponentName name,
              @NonNull CustomTabsClient client) {
            customTabsClient = client;

            // Warm up the browser process.
            customTabsClient.warmup(0);
            // Create a new browser session using the GMA Next-Gen SDK.
            customTabsSession = MobileAds.INSTANCE.registerCustomTabsSession(
                client,
                // Checks the "Digital Asset Link" to connect the postMessage channel.
                ORIGIN,
                // Optional parameter to receive the delegated callbacks.
                customTabsCallback);

            // Create a new browser session if the GMA Next-Gen SDK is
            // unable to create one.
            if (customTabsSession == null) {
              customTabsSession = client.newSession(customTabsCallback);
            }

            // Pass the custom tabs session into the intent.
            CustomTabsIntent intent = new CustomTabsIntent.Builder(customTabsSession).build();
            intent.launchUrl(MainActivity.this, Uri.parse("YOUR_URL"));
          }

          @Override
          public void onServiceDisconnected(ComponentName componentName) {
            // Remove the custom tabs client and custom tabs session.
            customTabsClient = null;
            customTabsSession = null;
          }
        }

    );
  }

  // Listen for events from the CustomTabsSession delegated by the GMA Next-Gen SDK.
  private final CustomTabsCallback customTabsCallback = new CustomTabsCallback() {
    @Override
    public void onNavigationEvent(int navigationEvent, @Nullable Bundle extras) {
      // Called when a navigation event happens.
      super.onNavigationEvent(navigationEvent, extras);
    }

    @Override
    public void onMessageChannelReady(@Nullable Bundle extras) {
      // Called when the channel is ready for sending and receiving messages on both
      // ends.
      // This frequently happens, such as each time the SDK requests a
      // new channel.
      super.onMessageChannelReady(extras);
    }

    @Override
    public void onPostMessage(@NonNull String message, @Nullable Bundle extras) {
      // Called when a tab controlled by this CustomTabsSession has sent a postMessage.
      super.onPostMessage(message, extras);
    }

    @Override
    public void onRelationshipValidationResult(int relation, @NonNull Uri requestedOrigin,
        boolean result, @Nullable Bundle extras) {
      // Called when a relationship validation result is available.
      super.onRelationshipValidationResult(relation, requestedOrigin, result, extras);
    }

    @Override
    public void onActivityResized(int height, int width, @NonNull Bundle extras) {
      // Called when the tab is resized.
      super.onActivityResized(height, width, extras);
    }

    @Override
    public void extraCallback(@NonNull String callbackName, @Nullable Bundle args) {
      super.extraCallback(callbackName, args);
    }

    @Nullable
    @Override
    public Bundle extraCallbackWithResult(@NonNull String callbackName, @Nullable Bundle args) {
      return super.extraCallbackWithResult(callbackName, args);
    }
  };
}