מודעות מותאמות מסוג Advanced

בחירת פלטפורמה: Android iOS

הצגת NativeAd

כשמודעה מותאמת נטענת, ה-Google Mobile Ads SDK מפעיל את המאזין של פורמט המודעה התואם. לאחר מכן, האפליקציה שלכם אחראית להצגת המודעה, אבל היא לא חייבת לעשות זאת באופן מיידי. כדי להקל על הצגת פורמטים של מודעות שהוגדרו על ידי המערכת, ב-SDK יש כמה משאבים שימושיים, כפי שמתואר בהמשך.

הגדרת הכיתה NativeAdView

מגדירים את הכיתה NativeAdView. הכיתה הזו היא כיתה מסוג ViewGroup, והיא מאגר ברמה העליונה של כיתה NativeAdView. כל תצוגה של מודעה מותאמת מכילה נכסים של מודעות מותאמות, כמו רכיב התצוגה MediaView או רכיב התצוגה Title, שחייבים להיות צאצאים של האובייקט NativeAdView.

פריסה של XML

מוסיפים לפרויקט קובץ XML NativeAdView:

<com.google.android.gms.ads.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.gms.ads.nativead.NativeAdView>

Jetpack פיתוח נייטיב

כוללים את המודול JetpackComposeDemo/compose-util, שכולל כלי עזר ליצירת NativeAdView והנכסים שלו.

באמצעות המודול compose-util, יוצרים 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.
        }
    }

טיפול ב-AAD מותאם לשפת האם שנטען

כשמודעה מותאמת נטענת, מטפלים באירוע הקריאה החוזרת, מרחיבים את התצוגה של המודעה המותאמת ומוסיפים אותה להיררכיית התצוגות:

Java

AdLoader.Builder builder = new AdLoader.Builder(this, "ca-app-pub-3940256099942544/2247696110")
    .forNativeAd(new NativeAd.OnNativeAdLoadedListener() {
        @Override
        public void onNativeAdLoaded(NativeAd nativeAd) {
            // Assumes you have a placeholder FrameLayout in your View layout
            // (with ID fl_adplaceholder) where the ad is to be placed.
            FrameLayout frameLayout =
                findViewById(R.id.fl_adplaceholder);
            // Assumes that your ad layout is in a file call native_ad_layout.xml
            // in the res/layout folder
            NativeAdView adView = (NativeAdView) getLayoutInflater()
                .inflate(R.layout.native_ad_layout, null);
            // This method sets the assets into the ad view.
            populateNativeAdView(nativeAd, adView);
            frameLayout.removeAllViews();
            frameLayout.addView(adView);
        }
});

Kotlin

val builder = AdLoader.Builder(this, "ca-app-pub-3940256099942544/2247696110")
    .forNativeAd { nativeAd ->
        // Assumes you have a placeholder FrameLayout in your View layout
        // (with ID fl_adplaceholder) where the ad is to be placed.
        val frameLayout: FrameLayout = findViewById(R.id.fl_adplaceholder)
        // Assumes that your ad layout is in a file call native_ad_layout.xml
        // in the res/layout folder
        val adView = layoutInflater
                .inflate(R.layout.native_ad_layout, null) as NativeAdView
        // This method sets the assets into the ad view.
        populateNativeAdView(nativeAd, adView)
        frameLayout.removeAllViews()
        frameLayout.addView(adView)
    }

Jetpack פיתוח נייטיב

@Composable
/** Load and display a native ad. */
fun NativeScreen() {
  var nativeAd by remember { mutableStateOf<NativeAd?>(null) }
  val context = LocalContext.current
  var isDisposed by remember { mutableStateOf(false) }

  DisposableEffect(Unit) {
    // Load the native ad when we launch this screen
    loadNativeAd(
      context = context,
      onAdLoaded = { ad ->
        // Handle the native ad being loaded.
        if (!isDisposed) {
          nativeAd = ad
        } else {
          // Destroy the native ad if loaded after the screen is disposed.
          ad.destroy()
        }
      },
    )
    // Destroy the native ad to prevent memory leaks when we dispose of this screen.
    onDispose {
      isDisposed = true
      nativeAd?.destroy()
      nativeAd = null
    }
  }

  // Display the native ad view with a user defined template.
  nativeAd?.let { adValue -> DisplayNativeAdView(adValue) }
}

fun loadNativeAd(context: Context, onAdLoaded: (NativeAd) -> Unit) {
  val adLoader =
    AdLoader.Builder(context, NATIVE_AD_UNIT_ID)
      .forNativeAd { nativeAd -> onAdLoaded(nativeAd) }
      .withAdListener(
        object : AdListener() {
          override fun onAdFailedToLoad(error: LoadAdError) {
            Log.e(TAG, "Native ad failed to load: ${error.message}")
          }

          override fun onAdLoaded() {
            Log.d(TAG, "Native ad was loaded.")
          }

          override fun onAdImpression() {
            Log.d(TAG, "Native ad recorded an impression.")
          }

          override fun onAdClicked() {
            Log.d(TAG, "Native ad was clicked.")
          }
        }
      )
      .build()
  adLoader.loadAd(AdRequest.Builder().build())
}

חשוב לזכור שכל הנכסים של מודעה מותאמת מסוימת צריכים להיות ברנדרינג בתוך הפריסה NativeAdView. ‏Google Mobile Ads SDK מנסה לתעד אזהרה כשנכסים מותאמים נעשים רינדור מחוץ לפריסה של תצוגת מודעה מותאמת.

בנוסף, הכיתות של תצוגת המודעות מספקות שיטות לצורך רישום התצוגה שמשמשת כל נכס בנפרד, ושיטה אחת לרישום אובייקט NativeAd עצמו. רישום התצוגות באופן הזה מאפשר ל-SDK לטפל באופן אוטומטי במשימות כמו:

  • הקלטת קליקים
  • תיעוד חשיפות כשהפיקסל הראשון גלוי במסך
  • הצגת שכבת-העל של AdChoices

שכבת-העל של AdChoices

ערכת ה-SDK מוסיפה שכבת-על של AdChoices לכל צפייה במודעה. משאירים מקום בפינה המועדפת בתצוגה של המודעה המובנית כדי להציג את הלוגו של AdChoices שיתווסף באופן אוטומטי. בנוסף, חשוב שיהיה קל לראות את שכבת-העל של AdChoices, לכן צריך לבחור בקפידה את צבעי הרקע והתמונות. מידע נוסף על המראה והפונקציונליות של שכבת-העל זמין במאמר תיאורי השדות של מודעות מותאמות.

סימן למודעה

חובה להציג סימן למודעה כדי לציין שהצפייה היא מודעה. מידע נוסף זמין בהנחיות המדיניות שלנו.

קוד לדוגמה

כדי להציג מודעה מותאמת, צריך לבצע את השלבים הבאים:

  1. יוצרים מופע של הכיתה NativeAdView.
  2. לכל נכס שיצורף למודעה:

    1. מאכלסים את תצוגת הנכס באמצעות הנכס באובייקט המודעה.
    2. רושמים את תצוגת הנכס בכיתה NativeAdView.
  3. צריך לרשום את הערך MediaView אם הפריסה של המודעה המותאמת כוללת נכס מדיה גדול.

  4. רושמים את אובייקט המודעה בכיתה NativeAdView.

זוהי דוגמה לפונקציה שמוצגת בה NativeAd:

Java

private void displayNativeAd(ViewGroup parent, NativeAd ad) {

  // Inflate a layout and add it to the parent ViewGroup.
  LayoutInflater inflater = (LayoutInflater) parent.getContext()
          .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  NativeAdView adView = (NativeAdView) inflater
          .inflate(R.layout.ad_layout_file, parent);

  // Locate the view that will hold the headline, set its text, and call the
  // NativeAdView's setHeadlineView method to register it.
  TextView headlineView = adView.findViewById<TextView>(R.id.ad_headline);
  headlineView.setText(ad.getHeadline());
  adView.setHeadlineView(headlineView);

  // Repeat the process for the other assets in the NativeAd
  // using additional view objects (Buttons, ImageViews, etc).

  // If the app is using a MediaView, it should be
  // instantiated and passed to setMediaView. This view is a little different
  // in that the asset is populated automatically, so there's one less step.
  MediaView mediaView = (MediaView) adView.findViewById(R.id.ad_media);
  adView.setMediaView(mediaView);

  // Call the NativeAdView's setNativeAd method to register the
  // NativeAdObject.
  adView.setNativeAd(ad);

  // Ensure that the parent view doesn't already contain an ad view.
  parent.removeAllViews();

  // Place the AdView into the parent.
  parent.addView(adView);
}

Kotlin

fun displayNativeAd(parent: ViewGroup, ad: NativeAd) {

  // Inflate a layout and add it to the parent ViewGroup.
  val inflater = parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)
          as LayoutInflater
  val adView = inflater.inflate(R.layout.ad_layout_file, parent) as NativeAdView

  // Locate the view that will hold the headline, set its text, and use the
  // NativeAdView's headlineView property to register it.
  val headlineView = adView.findViewById<TextView>(R.id.ad_headline)
  headlineView.text = ad.headline
  adView.headlineView = headlineView

  // Repeat the process for the other assets in the NativeAd using
  // additional view objects (Buttons, ImageViews, etc).

  val mediaView = adView.findViewById<MediaView>(R.id.ad_media)
  adView.mediaView = mediaView

  // Call the NativeAdView's setNativeAd method to register the
  // NativeAdObject.
  adView.setNativeAd(ad)

  // Ensure that the parent view doesn't already contain an ad view.
  parent.removeAllViews()

  // Place the AdView into the parent.
  parent.addView(adView)
}

Jetpack פיתוח נייטיב

@Composable
/** Display a native ad with a user defined template. */
fun DisplayNativeAdView(nativeAd: NativeAd) {
  val context = LocalContext.current
  Box(modifier = Modifier.padding(8.dp).wrapContentHeight(Alignment.Top)) {
    // Call the NativeAdView composable to display the native ad.
    NativeAdView {
      // Inside the NativeAdView composable, display the native ad assets.
      Column(Modifier.align(Alignment.TopStart).wrapContentHeight(Alignment.Top)) {
        // Display the ad attribution.
        NativeAdAttribution(text = context.getString(R.string.attribution))
        Row {
          // If available, display the icon asset.
          nativeAd.icon?.let { icon ->
            NativeAdIconView(Modifier.padding(5.dp)) {
              icon.drawable?.toBitmap()?.let { bitmap ->
                Image(bitmap = bitmap.asImageBitmap(), "Icon")
              }
            }
          }
          Column {
            // If available, display the headline asset.
            nativeAd.headline?.let {
              NativeAdHeadlineView {
                Text(text = it, style = MaterialTheme.typography.headlineLarge)
              }
            }
            // If available, display the star rating asset.
            nativeAd.starRating?.let {
              NativeAdStarRatingView {
                Text(text = "Rated $it", style = MaterialTheme.typography.labelMedium)
              }
            }
          }
        }

        // If available, display the body asset.
        nativeAd.body?.let { NativeAdBodyView { Text(text = it) } }
        // Display the media asset.
        NativeAdMediaView(Modifier.fillMaxWidth().height(500.dp).fillMaxHeight())

        Row(Modifier.align(Alignment.End).padding(5.dp)) {
          // If available, display the price asset.
          nativeAd.price?.let {
            NativeAdPriceView(Modifier.padding(5.dp).align(Alignment.CenterVertically)) {
              Text(text = it)
            }
          }
          // If available, display the store asset.
          nativeAd.store?.let {
            NativeAdStoreView(Modifier.padding(5.dp).align(Alignment.CenterVertically)) {
              Text(text = it)
            }
          }
          // If available, display the call to action asset.
          // Note: The Jetpack Compose button implements a click handler which overrides the native
          // ad click handler, causing issues. Use the NativeAdButton which does not implement a
          // click handler. To handle native ad clicks, use the NativeAd AdListener onAdClicked
          // callback.
          nativeAd.callToAction?.let { callToAction ->
            NativeAdCallToActionView(Modifier.padding(5.dp)) { NativeAdButton(text = callToAction) }
          }
        }
      }
    }
  }
}

אלה המשימות הנפרדות:

  1. הרחבת הפריסה

    Java

    LayoutInflater inflater = (LayoutInflater) parent.getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    NativeAdView adView = (NativeAdView) inflater
            .inflate(R.layout.ad_layout_file, parent);
    

    Kotlin

    val inflater = parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)
            as LayoutInflater
    val adView = inflater.inflate(R.layout.ad_layout_file, parent) as NativeAdView
    

    הקוד הזה מנפח פריסה של XML שמכילה תצוגות להצגת מודעה רגילה, ולאחר מכן מאתר הפניה ל-NativeAdView. שימו לב שאפשר גם לעשות שימוש חוזר ב-NativeAdView קיים אם יש כזה בחלק או בפעילות, או אפילו ליצור מכונה באופן דינמי בלי להשתמש בקובץ פריסה.

  2. אכלוס ורישום של תצוגות הנכסים

    קוד לדוגמה שמאתר את התצוגה שמשמשת להצגת הכותרת, מגדיר את הטקסט שלה באמצעות נכס המחרוזת שסופק על ידי אובייקט המודעה ומרשם אותו באובייקט NativeAdView:

    Java

    TextView headlineView = adView.findViewById<TextView>(R.id.ad_headline);
    headlineView.setText(ad.getHeadline());
    adView.setHeadlineView(headlineView);
    

    Kotlin

    val headlineView = adView.findViewById<TextView>(R.id.ad_headline)
    headlineView.text = ad.headline
    adView.headlineView = headlineView
    

    צריך לחזור על התהליך הזה של איתור התצוגה, הגדרת הערך שלה והרשמה שלה ל-class של תצוגת המודעה לכל אחד מהנכסים שסופקו על ידי אובייקט המודעה המובנית שהאפליקציה תציג.

  3. טיפול בלחיצות

    אין להטמיע פונקציות טיפול בהקשות בהתאמה אישית בתצוגות מעל או בתוך תצוגת המודעה המובנית. המערכת מטפלת בלחיצות על נכסי תצוגת המודעה באמצעות ה-SDK, כל עוד אתם מאכלסים ומרשמים בצורה נכונה את תצוגות הנכסים, כפי שמתואר בקטע הקודם.

    כדי להאזין לקליק, מטמיעים את פונקציית ה-call back של הקליק ב-Google Mobile Ads SDK:

    Java

    AdLoader adLoader = new AdLoader.Builder(context, "ca-app-pub-3940256099942544/2247696110")
        // ...
        .withAdListener(new AdListener() {
            @Override
            public void onAdFailedToLoad(LoadAdError adError) {
                // Handle the failure by logging.
            }
            @Override
            public void onAdClicked() {
                // Log the click event or other custom behavior.
            }
        })
        .build();
    

    Kotlin

    val adLoader = AdLoader.Builder(this, "ca-app-pub-3940256099942544/2247696110")
        // ...
        .withAdListener(object : AdListener() {
            override fun onAdFailedToLoad(adError: LoadAdError) {
                // Handle the failure.
            }
            override fun onAdClicked() {
                // Log the click event or other custom behavior.
            }
        })
        .build()
    
  4. רישום של MediaView

    אם רוצים לכלול נכס תמונה ראשי בפריסת המודעה המותאמת, צריך להשתמש בנכס MediaView במקום בנכס ImageView.

    MediaView הוא View מיוחד שמיועד להצגת נכס המדיה הראשי, בין אם מדובר בסרטון ובין אם בתמונה.

    אפשר להגדיר את MediaView בפריסה של XML או ליצור אותו באופן דינמי. צריך למקם אותו בהיררכיית התצוגה של NativeAdView, בדיוק כמו כל תצוגה אחרת של נכס. אפליקציות שמשתמשות ב-MediaView צריכות לרשום אותו ב-NativeAdView:

    Java

     // Populate and register the media asset view.
     nativeAdView.setMediaView(nativeAdBinding.adMedia);
    

    Kotlin

     // Populate and register the media asset view.
     nativeAdView.mediaView = nativeAdBinding.adMedia
    

    ImageScaleType

    לכיתה MediaView יש מאפיין ImageScaleType כשמוצגות תמונות. כדי לשנות את אופן שינוי התמונה ב-MediaView, מגדירים את ImageView.ScaleType המתאים באמצעות השיטה setImageScaleType() של MediaView:

    Java

    mediaView.setImageScaleType(ImageView.ScaleType.CENTER_CROP);
    

    Kotlin

    mediaView.imageScaleType = ImageView.ScaleType.CENTER_CROP
    

    MediaContent

    הכיתה MediaContent מכילה את הנתונים שקשורים לתוכן המדיה של המודעה המוטמעת, שמוצג באמצעות הכיתה MediaView. כשהמאפיין MediaView mediaContent מוגדר עם מכונה של MediaContent:

    • אם נכס הווידאו זמין, הוא נשמר במטמון ומתחיל לפעול בתוך MediaView. כדי לבדוק אם נכס וידאו זמין, אפשר לבדוק את הערך של hasVideoContent().

    • אם המודעה לא מכילה נכס וידאו, המערכת מורידת את נכס ה-mainImage ומציבה אותו בתוך ה-MediaView במקום זאת.

    כברירת מחדל, mainImage הוא נכס התמונה הראשון שהורדתם. אם משתמשים ב-setReturnUrlsForImageAssets(true), הערך של mainImage הוא null וצריך להגדיר את נכס mainImage לתמונה שהורדתם באופן ידני. חשוב לזכור שהמערכת תשתמש בתמונה הזו רק אם אין נכס וידאו זמין.

  5. רישום אובייקט המודעה המותאמת

    בשלב האחרון הזה, אובייקט המודעה המותאמת נרשם בתצוגה שאחראית להצגתו.

    Java

    adView.setNativeAd(ad);
    

    Kotlin

    adView.setNativeAd(ad)
    

השמדת מודעה

כשמסיימים להציג את המודעה המותאמת, צריך למחוק אותה כדי שהמודעה תימחק כראוי.

Java

nativeAd.destroy();

Kotlin

nativeAd.destroy()

דוגמאות ב-GitHub

דוגמה להטמעה מלאה של מודעות מותאמות:

Java Kotlin JetpackCompose

השלבים הבאים

כדאי לעיין בנושאים הבאים: