Tải một quảng cáo xen kẽ

Quảng cáo xen kẽ là quảng cáo toàn màn hình xuất hiện tại các điểm chuyển tiếp trong ứng dụng, chẳng hạn như giữa các màn hình hoặc trong thời gian tạm dừng giữa các cấp độ của trò chơi. Người dùng có thể nhấn vào quảng cáo để truy cập vào đích đến hoặc đóng quảng cáo và quay lại ứng dụng. Để biết thông tin chi tiết, hãy xem Hướng dẫn về quảng cáo xen kẽ và nghiên cứu điển hình.

Hướng dẫn này trình bày cách tích hợp quảng cáo xen kẽ vào ứng dụng React Native.

Điều kiện tiên quyết

Android

ca-app-pub-3940256099942544/1033173712

iOS

ca-app-pub-3940256099942544/4411468910

Tải một quảng cáo

Để tải quảng cáo xen kẽ, hãy gọi phương thức load trên lớp InterstitialAd.

Ví dụ sau đây tải một quảng cáo xen kẽ khi thành công và ghi lại lỗi khi không thành công:

export async function loadInterstitialAd(
  adUnitId: string,
): Promise<InterstitialAd | null> {
  try {
    const ad = await InterstitialAd.load({adUnitId});
    return ad;
  } catch (error) {
    const loadError = error as LoadAdError;
    console.error('Failed to load interstitial ad:', loadError.message);
    return null;
  }
}

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

Trước khi hiển thị quảng cáo, hãy đặt trình nghe adEventCallback trên thực thể InterstitialAd đã tải. Trình nghe này nhận lệnh gọi lại cho các sự kiện trong vòng đời của quảng cáo, chẳng hạn như quảng cáo xuất hiện trên màn hình hoặc người dùng nhấn vào quảng cáo. Để biết các lệnh gọi lại hiện có, hãy xem AdEventCallback.

Ví dụ sau đây đặt lệnh gọi lại để theo dõi các sự kiện quảng cáo:

export function registerAdEvents(ad: InterstitialAd) {
  ad.adEventCallback = {
    // Called when the ad is presented on screen.
    onAdShowedFullScreenContent: () => {
      console.log('Interstitial ad showed full screen content.');
    },
    // Called when the ad is closed by the user.
    onAdDismissedFullScreenContent: () => {
      console.log('Interstitial ad dismissed full screen content.');
      ad.destroy();
    },
    // Called when presentation fails.
    onAdFailedToShowFullScreenContent: (error) => {
      console.error('Failed to show interstitial ad:', error);
      ad.destroy();
    },
    // Called when an impression is recorded.
    onAdImpression: () => {
      console.log('Interstitial ad recorded an impression.');
    },
    // Called when the user taps the ad.
    onAdClicked: () => {
      console.log('Interstitial ad was clicked.');
    },
    // Called when the ad is estimated to have earned money.
    onAdPaid: (adValue) => {
      console.log(
        `Interstitial ad paid: ${adValue.amountMicros}` +
          ` ${adValue.currencyCode}`,
      );
    },
  };
}

Ví dụ này cũng gọi phương thức destroy khi người dùng đóng quảng cáo hoặc khi quảng cáo không hiển thị. Quá trình này giải phóng tài nguyên mà quảng cáo đã sử dụng.

Hiển thị quảng cáo

Để hiển thị quảng cáo xen kẽ, hãy gọi phương thức show trên thực thể InterstitialAd đã tải.

Ví dụ sau đây cho thấy một quảng cáo xen kẽ:

export function showInterstitialAd(ad: InterstitialAd) {
  ad.show();
}

Xem ví dụ đầy đủ

Phần này trình bày ví dụ đầy đủ về cách tích hợp quảng cáo xen kẽ vào ứng dụng React Native.

Ví dụ sau đây tích hợp quảng cáo vào một thành phần React Native, quản lý thực thể quảng cáo ở trạng thái và cung cấp các chế độ kiểm soát để tải và hiển thị quảng cáo:

export function InterstitialSingleLoadScreen() {
  const [ad, setAd] = useState<InterstitialAd | null>(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [status, setStatus] = useState<string>('Idle');

  useEffect(() => {
    return () => {
      ad?.destroy();
    };
  }, [ad]);

  const handleLoad = async () => {
    setStatus('Loading Interstitial ad...');
    const loadedAd = await loadInterstitialAd(INTERSTITIAL_AD_UNIT_ID);
    if (loadedAd) {
      registerAdEvents(loadedAd);
      const onDismiss =
        loadedAd.adEventCallback?.onAdDismissedFullScreenContent;
      loadedAd.adEventCallback = {
        ...loadedAd.adEventCallback,
        onAdDismissedFullScreenContent: () => {
          onDismiss?.();
          setStatus('Ad dismissed.');
        },
      };
      setAd((prevAd) => {
        prevAd?.destroy();
        return loadedAd;
      });
      setIsLoaded(true);
      setStatus('Interstitial ad loaded!');
    } else {
      setStatus('Failed to load Interstitial ad.');
    }
  };

  const handleShow = () => {
    if (ad) {
      showInterstitialAd(ad);
      setIsLoaded(false);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Interstitial Ad</Text>
      <Text style={styles.status}>Status: {status}</Text>
      <View style={styles.buttonGroup}>
        <Button title="Load Ad" onPress={handleLoad} />
        <View style={styles.spacerSmall} />
        <Button title="Show Ad" onPress={handleShow} disabled={!isLoaded} />
      </View>
    </View>
  );
}

Các bước tiếp theo

Sau khi bạn tích hợp quảng cáo xen kẽ, hãy khám phá các chủ đề sau: