Thiết lập quảng cáo xen kẽ có tặng thưởng

Next-Gen SDK.

Quảng cáo xen kẽ có tặng thưởng là một định dạng cho phép bạn tặng thưởng cho những quảng cáo tự động xuất hiện tại các điểm chuyển tiếp tự nhiên của ứng dụng. Không giống như quảng cáo có tặng thưởng, người dùng không bắt buộc phải chọn xem quảng cáo xen kẽ có tặng thưởng.

Tài liệu hướng dẫn này giải thích cách tích hợp quảng cáo xen kẽ có tặng thưởng vào một ứng dụng Android.

Trước khi bắt đầu

Trước khi tiếp tục, hãy làm như sau:

  • Thiết lập GMA Next-Gen SDK.
  • Sử dụng mã đơn vị quảng cáo xen kẽ có tặng thưởng thử nghiệm /21775744923/example/rewarded-interstitial.
    • Khi tạo và thử nghiệm ứng dụng, hãy nhớ sử dụng quảng cáo thử nghiệm thay vì quảng cáo đang chạy thực tế. Nếu không làm như vậy, chúng tôi có thể tạm ngưng tài khoản của bạn.
    • Trước khi xuất bản ứng dụng, hãy thay thế mã này bằng mã đơn vị quảng cáo của bạn.
    • Để biết thông tin chi tiết về quảng cáo thử nghiệm GMA Next-Gen SDK, hãy xem bài viết Bật quảng cáo thử nghiệm.

Tìm hiểu về tính năng tải trước quảng cáo

Tính năng tải trước quảng cáo trong GMA Next-Gen SDK tự động hoá việc tải và lưu quảng cáo vào bộ nhớ đệm.

Tính năng tải trước quảng cáo mang lại những lợi ích sau:

  • Quản lý thông tin tham chiếu: duy trì thông tin tham chiếu cho đến khi quảng cáo xuất hiện.
  • Tự động tải lại: tải một quảng cáo mới khi quảng cáo được truy xuất từ bộ nhớ đệm.
  • Quản lý các lần thử lại: tải một quảng cáo mới khi một quảng cáo không tải được.
  • Xử lý thời gian hết hạn: làm mới quảng cáo trước khi hết hạn.
  • Tối ưu hoá bộ nhớ đệm: tối ưu hoá thứ tự bộ nhớ đệm để phân phối quảng cáo có mức độ ưu tiên cao nhất.

Bắt đầu tải trước quảng cáo

Để bắt đầu tải trước quảng cáo, hãy gọi phương thức start một lần khi khởi động ứng dụng. Sau khi bạn gọi phương thức start, GMA Next-Gen SDK sẽ tự động tải trước quảng cáo và thử lại các yêu cầu không thành công cho cấu hình được tải trước.

Ví dụ sau đây cho biết cách bắt đầu tải trước quảng cáo:

Kotlin

// Call start() once after SDK initialization.
// Preload only one ad unit per format to optimize performance.
val adRequest = AdRequest.Builder(adUnitId).build()
val preloadConfig = PreloadConfiguration(adRequest)
RewardedInterstitialAdPreloader.start(adUnitId, preloadConfig)

Java

// Call start() once after SDK initialization.
// Preload only one ad unit per format to optimize performance.
AdRequest adRequest = new AdRequest.Builder(adUnitId).build();
PreloadConfiguration preloadConfig = new PreloadConfiguration(adRequest);
RewardedInterstitialAdPreloader.start(adUnitId, preloadConfig);

Thay thế AD_UNIT_ID bằng mã đơn vị quảng cáo của bạn.

Ví dụ trước cho thấy cách sử dụng mã đơn vị quảng cáo làm mã nhận dạng tải trước. Mã nhận dạng tải trước là một giá trị nhận dạng chuỗi mà bạn tạo để xác định cấu hình tải trước quảng cáo. Nếu ứng dụng của bạn yêu cầu nhiều cấu hình nhắm mục tiêu cho cùng một mã đơn vị quảng cáo, hãy truyền một giá trị nhận dạng chuỗi tuỳ chỉnh.

Nhận và hiển thị quảng cáo được tải trước

Khi bạn muốn hiển thị quảng cáo, hãy gọi phương thức pollAd. GMA Next-Gen SDK truy xuất một quảng cáo có sẵn và tự động tải trước quảng cáo tiếp theo ở chế độ nền. Nếu không có quảng cáo nào, GMA Next-Gen SDK sẽ không trả về quảng cáo.

Khi bạn có một đối tượng quảng cáo có sẵn, hãy gọi phương thức show để hiển thị quảng cáo. Sử dụng trình nghe phần thưởng để xử lý các sự kiện tặng thưởng. Ví dụ sau đây cho thấy cách truy xuất và hiển thị một quảng cáo được tải trước:

Kotlin

private fun pollAndShowAd(activity: Activity, adUnitId: String) {
  // Polling returns the next available ad and loads another ad in the background.
  val ad = RewardedInterstitialAdPreloader.pollAd(adUnitId)
  if (ad == null) {
    Log.e(TAG, "Rewarded interstitial ad is not available.")
    return
  }

  // Interact with the ad object as needed.
  Log.d(TAG, "Rewarded interstitial ad response info: ${ad.getResponseInfo()}")
  ad.adEventCallback =
    object : RewardedInterstitialAdEventCallback {
      override fun onAdImpression() {
        Log.d(TAG, "Rewarded interstitial ad recorded an impression.")
      }
    }
  ad.show(activity) { rewardItem -> Log.d(TAG, "User earned reward: ${rewardItem.amount}") }
}

Java

private void pollAndShowAd(Activity activity, String adUnitId) {
  // Polling returns the next available ad and loads another ad in the background.
  final RewardedInterstitialAd ad = RewardedInterstitialAdPreloader.pollAd(adUnitId);

  // Interact with the ad object as needed.
  if (ad == null) {
    Log.e(TAG, "Rewarded interstitial ad is not available.");
    return;
  }

  Log.d(TAG, "Rewarded interstitial ad response info: " + ad.getResponseInfo());
  ad.setAdEventCallback(
      new RewardedInterstitialAdEventCallback() {
        @Override
        public void onAdImpression() {
          Log.d(TAG, "Rewarded interstitial ad recorded an impression.");
        }
      });

  // Show the ad.
  ad.show(
      activity,
      rewardItem -> {
        Log.d(TAG, "User earned reward: " + rewardItem.getAmount());
      });
}

Tránh gọi phương thức pollAd cho đến khi bạn sẵn sàng hiển thị quảng cáo. Để đọc thông tin phản hồi quảng cáo mà không hiển thị, hãy xem phần Đọc thông tin phản hồi.

Theo dõi các sự kiện quảng cáo

Trước khi hiển thị quảng cáo, hãy theo dõi các sự kiện quảng cáo. Ví dụ sau đây cho thấy cách đăng ký các lệnh gọi lại cho các sự kiện quảng cáo:

Kotlin

private fun listenToAdEvents() {
  // Listen for ad events.
  val ad = rewardedInterstitialAd
  if (ad == null) {
    Log.e(TAG, "Rewarded interstitial ad is not ready yet.")
    return
  }

  ad.adEventCallback =
    object : RewardedInterstitialAdEventCallback {
      override fun onAdShowedFullScreenContent() {
        // Rewarded interstitial ad did show.
      }

      override fun onAdDismissedFullScreenContent() {
        // Rewarded interstitial ad did dismiss.
        rewardedInterstitialAd = null
      }

      override fun onAdFailedToShowFullScreenContent(
        fullScreenContentError: FullScreenContentError
      ) {
        // Rewarded interstitial ad failed to show.
        Log.e(TAG, "Rewarded interstitial ad failed to show: ${fullScreenContentError.message}")
      }

      override fun onAdImpression() {
        // Rewarded interstitial ad did record an impression.
      }

      override fun onAdClicked() {
        // Rewarded interstitial ad did record a click.
      }
    }
}

Java

private void listenToAdEvents() {
  // Listen for ad events.
  if (rewardedInterstitialAd == null) {
    Log.e(TAG, "Rewarded interstitial ad is not ready yet.");
    return;
  }

  rewardedInterstitialAd.setAdEventCallback(
      new RewardedInterstitialAdEventCallback() {
        @Override
        public void onAdShowedFullScreenContent() {
          // Rewarded interstitial ad did show.
        }

        @Override
        public void onAdDismissedFullScreenContent() {
          // Rewarded interstitial ad did dismiss.
          rewardedInterstitialAd = null;
        }

        @Override
        public void onAdFailedToShowFullScreenContent(
            @NonNull FullScreenContentError fullScreenContentError) {
          // Rewarded interstitial ad failed to show.
          Log.e(
              TAG,
              "Rewarded interstitial ad failed to show: " + fullScreenContentError.getMessage());
        }

        @Override
        public void onAdImpression() {
          // Rewarded interstitial ad did record an impression.
        }

        @Override
        public void onAdClicked() {
          // Rewarded interstitial ad did record a click.
        }
      });
}

Không bắt buộc: Xác thực lệnh gọi lại của tính năng xác minh phía máy chủ (SSV)

Nếu ứng dụng của bạn cần có thêm dữ liệu trong lệnh gọi lại xác minh phía máy chủ, hãy sử dụng tính năng dữ liệu tuỳ chỉnh của quảng cáo xen kẽ có tặng thưởng. Mọi giá trị chuỗi được đặt cho đối tượng quảng cáo xen kẽ có tặng thưởng đều được truyền đến tham số truy vấn custom_data của lệnh gọi lại SSV. Nếu bạn không đặt giá trị dữ liệu tuỳ chỉnh, thì giá trị tham số truy vấn custom_data sẽ không hiển thị trong lệnh gọi lại SSV.

Mã mẫu sau đây cho biết cách đặt dữ liệu tuỳ chỉnh cho đối tượng quảng cáo xen kẽ có tặng thưởng trước khi hiển thị quảng cáo:

Kotlin

RewardedInterstitialAd.load(
  context,
  AD_UNIT_ID,
  AdRequest.Builder().build(),
  object : RewardedInterstitialAdLoadCallback() {
    override fun onAdLoaded(ad: RewardedInterstitialAd) {
      rewardedInterstitialAd = ad
      val options =
        ServerSideVerificationOptions.Builder().setCustomData("SAMPLE_CUSTOM_DATA_STRING").build()
      rewardedInterstitialAd?.setServerSideVerificationOptions(options)
    }
  },
)

Java

RewardedInterstitialAd.load(
    context,
    AD_UNIT_ID,
    new AdRequest.Builder().build(),
    new RewardedInterstitialAdLoadCallback() {
      @Override
      public void onAdLoaded(RewardedInterstitialAd ad) {
        rewardedInterstitialAd = ad;
        ServerSideVerificationOptions options =
            new ServerSideVerificationOptions.Builder()
                .setCustomData("SAMPLE_CUSTOM_DATA_STRING")
                .build();
        rewardedInterstitialAd.setServerSideVerificationOptions(options);
      }
    });

Thay thế SAMPLE_CUSTOM_DATA_STRING bằng dữ liệu tuỳ chỉnh của bạn.

Không bắt buộc: Theo dõi các sự kiện tải trước

Khi bạn bắt đầu tải trước quảng cáo, hãy đăng ký các sự kiện tải trước để nhận thông báo khi quảng cáo tải trước thành công, không tải trước được hoặc bộ nhớ đệm quảng cáo đã hết.

Ví dụ sau đây cho thấy cách đăng ký các sự kiện quảng cáo tải trước:

Kotlin

val preloadCallback =
  // [Important] Don't call ad preloader start() or pollAd() within the PreloadCallback.
  object : PreloadCallback {
    override fun onAdFailedToPreload(preloadId: String, adError: LoadAdError) {
      Log.d(
        TAG,
        "Rewarded interstitial preload ad $preloadId failed to load with error: ${adError.message}",
      )
    }

    override fun onAdsExhausted(preloadId: String) {
      Log.i(TAG, "Rewarded interstitial preload ad $preloadId is not available")
      // [Important] Don't call ad preloader start() or pollAd() from onAdsExhausted.
    }

    override fun onAdPreloaded(preloadId: String, responseInfo: ResponseInfo) {
      Log.i(TAG, "Rewarded interstitial preload ad $preloadId is available")
    }
  }
val adRequest = AdRequest.Builder(adUnitId).build()
val preloadConfig = PreloadConfiguration(adRequest)
RewardedInterstitialAdPreloader.start(adUnitId, preloadConfig, preloadCallback)

Java

PreloadCallback preloadCallback =
    // [Important] Don't call ad preloader start() or pollAd() within the PreloadCallback.
    new PreloadCallback() {
      @Override
      public void onAdFailedToPreload(@NonNull String preloadId, @NonNull LoadAdError adError) {
        Log.d(
            TAG,
            String.format(
                "Rewarded interstitial preload ad %s failed to load with error: %s",
                preloadId, adError.getMessage()));
        // [Optional] Get the error response info for additional details.
        // ResponseInfo responseInfo = adError.getResponseInfo();
      }

      @Override
      public void onAdsExhausted(@NonNull String preloadId) {
        Log.i(TAG, "Rewarded interstitial preload ad " + preloadId + " is not available");
        // [Important] Don't call ad preloader start() or pollAd() from onAdsExhausted.
      }

      @Override
      public void onAdPreloaded(@NonNull String preloadId, @NonNull ResponseInfo responseInfo) {
        Log.i(TAG, "Rewarded interstitial preload ad " + preloadId + " is available");
      }
    };
AdRequest adRequest = new AdRequest.Builder(adUnitId).build();
PreloadConfiguration preloadConfig = new PreloadConfiguration(adRequest);
RewardedInterstitialAdPreloader.start(adUnitId, preloadConfig, preloadCallback);

Khi một quảng cáo không tải được, GMA Next-Gen SDK sẽ tự động tải trước quảng cáo và thử lại các yêu cầu không thành công cho cấu hình được tải trước.

Không bắt buộc: Kiểm tra xem có quảng cáo hay không

Nếu bạn cần biết liệu có quảng cáo hay không, hãy kiểm tra tình trạng có quảng cáo. Ví dụ sau đây cho biết cách kiểm tra xem quảng cáo được tải trước có dùng được hay không:

Kotlin

private fun isAdAvailable(adUnitId: String): Boolean {
  return RewardedInterstitialAdPreloader.isAdAvailable(adUnitId)
}

Java

private boolean isAdAvailable(String adUnitId) {
  return RewardedInterstitialAdPreloader.isAdAvailable(adUnitId);
}

Không bắt buộc: Đặt dung lượng bộ nhớ đệm

Dung lượng bộ nhớ đệm kiểm soát số lượng quảng cáo được tải trước và lưu trữ trong bộ nhớ. Theo mặc định, Google tối ưu hoá kích thước vùng đệm để cân bằng mức tiêu thụ bộ nhớ và độ trễ khi phân phát quảng cáo. Bạn có thể đặt dung lượng bộ nhớ đệm tuỳ chỉnh để tăng số lượng quảng cáo được lưu giữ trong bộ nhớ. Chúng tôi đề xuất dung lượng bộ nhớ đệm tối đa là 4.

Ví dụ sau đây cho thấy cách đặt dung lượng bộ nhớ đệm là 4 quảng cáo được tải trước:

Kotlin

val adRequest = AdRequest.Builder(adUnitId).build()
// Maintain small or default buffer size unless rapid transitions are expected.
val preloadConfig = PreloadConfiguration(adRequest, bufferSize = 4)
RewardedInterstitialAdPreloader.start(adUnitId, preloadConfig)

Java

// Maintain small or default buffer size unless rapid transitions are expected.
AdRequest adRequest = new AdRequest.Builder(adUnitId).build();
PreloadConfiguration preloadConfig = new PreloadConfiguration(adRequest, 4);
RewardedInterstitialAdPreloader.start(adUnitId, preloadConfig);

Giới hạn bộ nhớ đệm tải trước

GMA Next-Gen SDK áp dụng giới hạn trên toàn ứng dụng đối với tổng số quảng cáo được tải trước trên tất cả các đơn vị quảng cáo và mã nhận dạng tải trước:

  • Giới hạn mặc định: Google lưu trữ tối đa 6 quảng cáo được tải trước trong bộ nhớ. Giới hạn này áp dụng cho tất cả các định dạng và mã nhận dạng tải trước.
  • Bạn nên giữ dung lượng bộ nhớ đệm là 2 hoặc 3 cho mỗi mã nhận dạng tải trước.

Không bắt buộc: Dừng tải trước quảng cáo

Nếu không cần hiển thị lại quảng cáo cho một mã tải trước cụ thể trong phiên, bạn có thể dừng tải trước quảng cáo. Để ngừng tải quảng cáo cho một mã nhận dạng tải trước cụ thể, hãy gọi phương thức destroy bằng mã nhận dạng tải trước. Việc gọi phương thức destroy sẽ xoá tất cả quảng cáo được tải trước liên kết với mã nhận dạng tải trước khỏi bộ nhớ đệm.

Ví dụ sau đây cho thấy cách dừng tải trước quảng cáo:

Kotlin

private fun stopPreloading(adUnitId: String) {
  // Stops the preloading and destroy preloaded ads.
  RewardedInterstitialAdPreloader.destroy(adUnitId)
}

Java

private void stopPreloading(String adUnitId) {
  // Stops the preloading and destroy preloaded ads.
  RewardedInterstitialAdPreloader.destroy(adUnitId);
}

Không bắt buộc: Đọc thông tin phản hồi

Đọc thông tin phản hồi của quảng cáo được tải trước tiếp theo mà không cần xoá quảng cáo khỏi bộ nhớ đệm.

Ví dụ sau đây cho biết cách đọc thông tin phản hồi về quảng cáo được tải sẵn tiếp theo:

Kotlin

val responseInfo = RewardedInterstitialAdPreloader.peekAdResponseInfo(preloadId)
if (responseInfo == null) {
  Log.e(TAG, "Failed to peek ad response info.")
  return
}

Log.d(TAG, "Peeked ad response ID: ${responseInfo.responseId}")

Java

ResponseInfo responseInfo = RewardedInterstitialAdPreloader.peekAdResponseInfo(preloadId);
if (responseInfo == null) {
  Log.e(TAG, "Failed to peek ad response info.");
  return;
}

Log.d(TAG, "Peeked ad response ID: " + responseInfo.getResponseId());