Quảng cáo gốc

Khi một quảng cáo gốc tải, SDK Quảng cáo của Google trên thiết bị di động (bản thử nghiệm) sẽ gọi trình xử lý để có định dạng quảng cáo tương ứng. Sau đó, ứng dụng của bạn sẽ chịu trách nhiệm hiển thị quảng cáo, mặc dù ứng dụng không nhất thiết phải làm việc đó ngay lập tức. Để giúp hiển thị các định dạng quảng cáo do hệ thống xác định một cách dễ dàng hơn, SDK sẽ cung cấp một số tài nguyên hữu ích như mô tả bên dưới.

Xác định lớp NativeAdView

Xác định một lớp NativeAdView. Lớp này là một lớp ViewGroup và là vùng chứa cấp cao nhất cho một lớp NativeAdView. Mỗi khung hiển thị quảng cáo gốc đều chứa các thành phần quảng cáo gốc, chẳng hạn như phần tử khung hiển thị MediaView hoặc phần tử khung hiển thị Title. Các thành phần này phải là đối tượng con của đối tượng NativeAdView.

Bố cục XML

Thêm một NativeAdView XML vào dự án của bạn:

<com.google.android.libraries.ads.mobile.sdk.nativead.NativeAdView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <LinearLayout
    android:orientation="vertical">
        <LinearLayout
        android:orientation="horizontal">
          <ImageView
          android:id="@+id/ad_app_icon" />
          <TextView
            android:id="@+id/ad_headline" />
        </LinearLayout>
        <!--Add remaining assets such as the image and media view.-->
    </LinearLayout>
</com.google.android.libraries.ads.mobile.sdk.nativead.NativeAdView>

Jetpack Compose

Bao gồm mô-đun JetpackComposeDemo/compose-util, trong đó có các trình trợ giúp để tạo NativeAdView và tài sản của mô-đun này.

Sử dụng mô-đun compose-util, hãy tạo một NativeAdView:

  import com.google.android.gms.compose_util.NativeAdAttribution
  import com.google.android.gms.compose_util.NativeAdView

  @Composable
  /** Display a native ad with a user defined template. */
  fun DisplayNativeAdView(nativeAd: NativeAd) {
      NativeAdView {
          // Display the ad attribution.
          NativeAdAttribution(text = context.getString("Ad"))
          // Add remaining assets such as the image and media view.
        }
    }

Xử lý quảng cáo gốc đã tải

Khi quảng cáo gốc tải, hãy xử lý sự kiện gọi lại, tăng chế độ xem quảng cáo gốc và thêm chế độ xem đó vào hệ phân cấp chế độ xem:

Kotlin

// Build an ad request with native ad options to customize the ad.
val adTypes = listOf(NativeAd.NativeAdType.NATIVE)
val adRequest = NativeAdRequest
  .Builder("ca-app-pub-3940256099942544/2247696110", adTypes)
  .build()

val adCallback =
  object : NativeAdLoaderCallback {
    override fun onNativeAdLoaded(nativeAd: NativeAd) {
      activity?.runOnUiThread {

        val nativeAdBinding = NativeAdBinding.inflate(layoutInflater)
        val adView = nativeAdBinding.root
        val frameLayout = myActivityLayout.nativeAdPlaceholder

        // Populate and register the native ad asset views.
        displayNativeAd(nativeAd, nativeAdBinding)

        // Remove all old ad views and add the new native ad
        // view to the view hierarchy.
        frameLayout.removeAllViews()
        frameLayout.addView(adView)
      }
    }
  }

// Load the native ad with our request and callback.
NativeAdLoader.load(adRequest, adCallback)

Java

// Build an ad request with native ad options to customize the ad.
List<NativeAd.NativeAdType> adTypes = Arrays.asList(NativeAd.NativeAdType.NATIVE);
NativeAdRequest adRequest = new NativeAdRequest
                                .Builder("ca-app-pub-3940256099942544/2247696110", adTypes)
                                .build();

NativeAdLoaderCallback adCallback = new NativeAdLoaderCallback() {
    @Override
    public void onNativeAdLoaded(NativeAd nativeAd) {
      if (getActivity() != null) {
        getActivity()
          .runOnUiThread(() -> {
            // Inflate the native ad view and add it to the view hierarchy.
            NativeAdBinding nativeAdBinding = NativeAdBinding.inflate(getLayoutInflater());
            NativeAdView adView = (NativeAdView) nativeAdBinding.getRoot();
            FrameLayout frameLayout = myActivityLayout.nativeAdPlaceholder;

            // Populate and register the native ad asset views.
            displayNativeAd(nativeAd, nativeAdBinding);

            // Remove all old ad views and add the new native ad
            // view to the view hierarchy.
            frameLayout.removeAllViews();
            frameLayout.addView(adView);
        });
      }
    }
};

// Load the native ad with our request and callback.
NativeAdLoader.load(adRequest, adCallback);

Xin lưu ý rằng tất cả thành phần của một quảng cáo gốc nhất định phải hiển thị bên trong bố cục NativeAdView. SDK Quảng cáo của Google trên thiết bị di động (thử nghiệm) sẽ tìm cách ghi nhật ký cảnh báo khi tài sản gốc hiển thị bên ngoài bố cục của chế độ xem quảng cáo gốc.

Các lớp chế độ xem quảng cáo cũng cung cấp phương thức dùng để đăng ký chế độ xem được sử dụng cho từng tài sản riêng lẻ và một phương thức để đăng ký chính đối tượng NativeAd. Việc đăng ký các chế độ xem theo cách này cho phép SDK tự động xử lý các công việc, chẳng hạn như:

  • Ghi lại các lượt nhấp
  • Ghi lại các lượt hiển thị khi pixel đầu tiên hiển thị trên màn hình
  • Hiển thị lớp phủ Lựa chọn quảng cáo

Hiển thị quảng cáo gốc

Ví dụ sau đây minh hoạ cách hiển thị một quảng cáo gốc:

Kotlin

private fun displayNativeAd(nativeAd: NativeAd, nativeAdBinding : NativeAdBinding) {
  // Set the native ad view elements.
  val nativeAdView = nativeAdBinding.root
  nativeAdView.advertiserView = nativeAdBinding.adAdvertiser
  nativeAdView.bodyView = nativeAdBinding.adBody
  nativeAdView.callToActionView = nativeAdBinding.adCallToAction
  nativeAdView.headlineView = nativeAdBinding.adHeadline
  nativeAdView.iconView = nativeAdBinding.adAppIcon
  nativeAdView.priceView = nativeAdBinding.adPrice
  nativeAdView.starRatingView = nativeAdBinding.adStars
  nativeAdView.storeView = nativeAdBinding.adStore

  // Set the view element with the native ad assets.
  nativeAdBinding.adAdvertiser.text = nativeAd.advertiser
  nativeAdBinding.adBody.text = nativeAd.body
  nativeAdBinding.adCallToAction.text = nativeAd.callToAction
  nativeAdBinding.adHeadline.text = nativeAd.headline
  nativeAdBinding.adAppIcon.setImageDrawable(nativeAd.icon?.drawable)
  nativeAdBinding.adPrice.text = nativeAd.price
  nativeAd.starRating?.toFloat().let { value ->
    nativeAdBinding.adStars.rating = value
  }
  nativeAdBinding.adStore.text = nativeAd.store

  // Hide views for assets that don't have data.
  nativeAdBinding.adAdvertiser.visibility = getAssetViewVisibility(nativeAd.advertiser)
  nativeAdBinding.adBody.visibility = getAssetViewVisibility(nativeAd.body)
  nativeAdBinding.adCallToAction.visibility = getAssetViewVisibility(nativeAd.callToAction)
  nativeAdBinding.adHeadline.visibility = getAssetViewVisibility(nativeAd.headline)
  nativeAdBinding.adAppIcon.visibility = getAssetViewVisibility(nativeAd.icon)
  nativeAdBinding.adPrice.visibility = getAssetViewVisibility(nativeAd.price)
  nativeAdBinding.adStars.visibility = getAssetViewVisibility(nativeAd.starRating)
  nativeAdBinding.adStore.visibility = getAssetViewVisibility(nativeAd.store)

  // Inform Google Mobile Ads SDK (beta) that you have finished populating
  // the native ad views with this native ad.
  nativeAdView.registerNativeAd(nativeAd, nativeAdBinding.adMedia)
}

/**
* Determines the visibility of an asset view based on the presence of its asset.
*
* @param asset The native ad asset to check for nullability.
* @return [View.VISIBLE] if the asset is not null, [View.INVISIBLE] otherwise.
*/
private fun getAssetViewVisibility(asset: Any?): Int {
  return if (asset == null) View.INVISIBLE else View.VISIBLE
}

Java

private void displayNativeAd(ad: NativeAd, nativeAdBinding : NativeAdBinding) {
  // Set the native ad view elements.
  NativeAdView nativeAdView = nativeAdBinding.getRoot();
  nativeAdView.setAdvertiserView(nativeAdBinding.adAdvertiser);
  nativeAdView.setBodyView(nativeAdBinding.adBody);
  nativeAdView.setCallToActionView(nativeAdBinding.adCallToAction);
  nativeAdView.setHeadlineView(nativeAdBinding.adHeadline);
  nativeAdView.setIconView(nativeAdBinding.adAppIcon);
  nativeAdView.setPriceView(nativeAdBinding.adPrice);
  nativeAdView.setStarRatingView(nativeAdBinding.adStars);
  nativeAdView.setStoreView(nativeAdBinding.adStore);

  // Set the view element with the native ad assets.
  nativeAdBinding.adAdvertiser.setText(nativeAd.getAdvertiser());
  nativeAdBinding.adBody.setText(nativeAd.getBody());
  nativeAdBinding.adCallToAction.setText(nativeAd.getCallToAction());
  nativeAdBinding.adHeadline.setText(nativeAd.getHeadline());
  if (nativeAd.getIcon() != null) {
      nativeAdBinding.adAppIcon.setImageDrawable(nativeAd.getIcon().getDrawable());
  }
  nativeAdBinding.adPrice.setText(nativeAd.getPrice());
  if (nativeAd.getStarRating() != null) {
      nativeAdBinding.adStars.setRating(nativeAd.getStarRating().floatValue());
  }
  nativeAdBinding.adStore.setText(nativeAd.getStore());

  // Hide views for assets that don't have data.
  nativeAdBinding.adAdvertiser.setVisibility(getAssetViewVisibility(nativeAd.getAdvertiser()));
  nativeAdBinding.adBody.setVisibility(getAssetViewVisibility(nativeAd.getBody()));
  nativeAdBinding.adCallToAction.setVisibility(getAssetViewVisibility(nativeAd.getCallToAction()));
  nativeAdBinding.adHeadline.setVisibility(getAssetViewVisibility(nativeAd.getHeadline()));
  nativeAdBinding.adAppIcon.setVisibility(getAssetViewVisibility(nativeAd.getIcon()));
  nativeAdBinding.adPrice.setVisibility(getAssetViewVisibility(nativeAd.getPrice()));
  nativeAdBinding.adStars.setVisibility(getAssetViewVisibility(nativeAd.getStarRating()));
  nativeAdBinding.adStore.setVisibility(getAssetViewVisibility(nativeAd.getStore()));

  // Inform Google Mobile Ads SDK (beta) that you have finished populating
  // the native ad views with this native ad.
  nativeAdView.registerNativeAd(nativeAd, nativeAdBinding.adMedia);
}

/**
* Determines the visibility of an asset view based on the presence of its asset.
*
* @param asset The native ad asset to check for nullability.
* @return {@link View#VISIBLE} if the asset is not null, {@link View#INVISIBLE} otherwise.
*/
private int getAssetViewVisibility(Object asset) {
    return (asset == null) ? View.INVISIBLE : View.VISIBLE;
}

Lớp phủ Lựa chọn quảng cáo

SDK sẽ thêm lớp phủ Lựa chọn quảng cáo vào mỗi chế độ xem quảng cáo. Hãy để trống một khoảng ở góc bạn muốn đặt chế độ xem quảng cáo gốc để hệ thống tự động chèn biểu trưng Lựa chọn quảng cáo. Ngoài ra, lớp phủ Lựa chọn quảng cáo phải trông thật dễ nhìn, vì vậy, bạn hãy chọn màu nền và hình ảnh phù hợp. Để biết thêm thông tin về hình thức và chức năng của lớp phủ, hãy xem Nội dung mô tả trường quảng cáo gốc.

Thuộc tính quảng cáo

Bạn phải hiển thị một thuộc tính quảng cáo để biểu thị rằng chế độ xem đó là quảng cáo. Hãy xem nguyên tắc chính sách của chúng tôi để biết thêm.

Xử lý lượt nhấp

Không triển khai bất kỳ trình xử lý lượt nhấp tuỳ chỉnh nào trên mọi chế độ xem ở trên hoặc trong chế độ xem quảng cáo gốc. SDK sẽ xử lý số lượt nhấp vào nội dung của lượt xem quảng cáo, chỉ cần bạn điền và đăng ký chính xác chế độ xem nội dung.

Để theo dõi lượt nhấp, hãy triển khai lệnh gọi lại lượt nhấp của SDK quảng cáo trên thiết bị di động của Google (beta):

Kotlin

private fun setEventCallback(nativeAd: NativeAd) {
  nativeAd.adEventCallback =
    object : NativeAdEventCallback {
      override fun onAdClicked() {
        Log.d(Constant.TAG, "Native ad recorded a click.")
      }
    }
}

Java

private void setEventCallback(NativeAd nativeAd) {
  nativeAd.setAdEventCallback(new NativeAdEventCallback() {
      @Override
      public void onAdClicked() {
        Log.d(Constant.TAG, "Native ad recorded a click.");
      }
  });
}

ImageScaleType

Lớp MediaView có thuộc tính ImageScaleType khi hiển thị hình ảnh. Nếu bạn muốn thay đổi cách chuyển tỉ lệ hình ảnh trong MediaView, hãy đặt ImageView.ScaleType tương ứng bằng cách sử dụng phương thức setImageScaleType() của MediaView:

Kotlin

nativeAdViewBinding.mediaView.imageScaleType = ImageView.ScaleType.CENTER_CROP

Java

nativeAdViewBinding.mediaView.setImageScaleType(ImageView.ScaleType.CENTER_CROP);

MediaContent

Lớp MediaContent chứa dữ liệu liên quan đến nội dung nghe nhìn của quảng cáo gốc. Nội dung này được hiển thị bằng cách sử dụng lớp MediaView. Khi bạn đặt thuộc tính MediaView mediaContent bằng một thực thể MediaContent:

  • Nếu có thành phần video, thì video đó sẽ được lưu vào vùng đệm và bắt đầu phát bên trong MediaView. Bạn có thể biết liệu quảng cáo có chứa thành phần video hay không bằng cách đánh dấu chọn hasVideoContent().

  • Nếu quảng cáo không chứa thành phần video, thì thành phần mainImage sẽ được tải xuống và đặt bên trong MediaView.

Huỷ quảng cáo

Sau khi bạn hiển thị quảng cáo gốc, hãy huỷ quảng cáo đó. Ví dụ sau đây sẽ huỷ một quảng cáo gốc:

Kotlin

nativeAd.destroy()

Java

nativeAd.destroy();

Các bước tiếp theo

Khám phá các chủ đề sau:

Ví dụ:

Tải xuống và chạy ứng dụng mẫu minh hoạ cách sử dụng SDK quảng cáo trên thiết bị di động của Google (bản thử nghiệm).