Caricare un singolo annuncio interstitial

Gli annunci interstitial sono annunci a schermo intero che vengono visualizzati nei punti di transizione dell'app, ad esempio tra una schermata e l'altra o durante la pausa tra i livelli di un gioco. Gli utenti possono toccare l'annuncio per visitare la destinazione o chiuderlo e tornare all'app. Per maggiori dettagli, consulta le indicazioni sugli annunci interstitial e un case study.

Questa guida mostra come integrare gli annunci interstitial in un'app React Native.

Prerequisiti

Android

ca-app-pub-3940256099942544/1033173712

iOS

ca-app-pub-3940256099942544/4411468910

Carica un annuncio

Per caricare un annuncio interstitial, chiama il metodo load nella classe InterstitialAd.

L'esempio seguente carica un annuncio interstitial in caso di esito positivo e registra un errore in caso di esito negativo:

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;
  }
}

Ascolta gli eventi degli annunci

Prima di mostrare l'annuncio, imposta il listener adEventCallback sull'istanza InterstitialAd caricata. Questo listener riceve callback per gli eventi del ciclo di vita degli annunci, ad esempio la visualizzazione dell'annuncio sullo schermo o il tocco dell'annuncio da parte di un utente. Per i callback disponibili, consulta AdEventCallback.

L'esempio seguente imposta i callback per ascoltare gli eventi annuncio:

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}`,
      );
    },
  };
}

Questo esempio chiama anche il metodo destroy quando un utente chiude l'annuncio o quando l'annuncio non viene mostrato. Questo processo rilascia le risorse utilizzate dall'annuncio.

Mostra l'annuncio

Per mostrare un annuncio interstitial, chiama il metodo show sull'istanza InterstitialAd caricata.

L'esempio seguente mostra un annuncio interstitial:

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

Visualizza l'esempio completo

Questa sezione illustra l'esempio completo per integrare un annuncio interstitial in un'app nativa React Native.

L'esempio seguente integra l'annuncio in un componente React Native, gestisce l'istanza dell'annuncio nello stato e fornisce i controlli per caricare e visualizzare l'annuncio:

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>
  );
}

Passaggi successivi

Dopo aver integrato gli annunci interstitial, consulta i seguenti argomenti: