نمایش آگهی بومی

پلاتفرم را انتخاب کنید: Android iOS Android (قدیمی)

وقتی آگهی بومی بار می‌شود، Google Mobile Ads SDK (Legacy) شنونده را برای قالب آگهی مربوطه فراخوانی می‌کند. سپس برنامه شما مسئول نمایش آگهی است، اگرچه لزوماً نباید این کار را فوراً انجام دهد. برای آسان‌تر کردن نمایش قالب‌های آگهی تعریف‌شده توسط سیستم، کیت توسعه نرم‌افزار چند منبع مفید ارائه می‌دهد که در زیر شرح داده شده است.

تعریف کردن کلاس NativeAdView

کلاس NativeAdView را تعریف می‌کند. این کلاس یک ViewGroup کلاس است و بالاترین سطح نگهدارنده برای کلاس NativeAdView است. هر نمای آگهی بومی حاوی دارایی‌های آگهی بومی است، مانند عنصر نمای MediaView یا عنصر نمای Title، که باید فرزند شیء NativeAdView باشد.

چیدمان XML

NativeAdView XML به پروژه اضافه کنید:

<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 Compose

  1. پوشه JetpackCompose Utilities را اضافه کنید. این پوشه شامل کمک‌کننده‌هایی برای ترکیب‌بندی دارایی‌ها و شیء NativeAdView است.

نوشتن 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.
        }
    }

مدیریت آگهی بومی بارشده

وقتی آگهی بومی بار می‌شود، رویداد فراخوانی را مدیریت کنید، نمای آگهی بومی را گسترش دهید، و آن را به سلسله‌مراتب نما اضافه کنید:

جاوا

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.
            displayNativeAd(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.
        displayNativeAd(nativeAd, adView)
        frameLayout.removeAllViews()
        frameLayout.addView(adView)
    }

Jetpack Compose

@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 (Legacy) تلاش می‌کند وقتی دارایی‌های بومی خارج از طرح‌بندی نمای آگهی بومی ارائه می‌شوند، هشداری را ثبت کند.

کلاس‌های نمای آگهی همچنین روش‌هایی را ارائه می‌دهند که برای ثبت نمای استفاده‌شده برای هر دارایی فردی و یکی برای ثبت خود شیء NativeAd استفاده می‌شود. ثبت نماها به این روش به کیت توسعه نرم‌افزار اجازه می‌دهد تا به‌طور خودکار تکالیفی مثل موارد زیر را انجام دهد:

  • کلیک‌های ضبط
  • ثبت ظهورها وقتی اولین پیکسل در صفحه نمایان می‌شود
  • درحال نمایش همپوشانی AdChoices

نمایش آگهی بومی

مثال زیر نحوه نمایش آگهی بومی را نشان می‌دهد:

جاوا

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 you use a MediaView, call theNativeAdView.setMediaView() method
  // before calling the NativeAdView.setNativeAd() method.
  MediaView mediaView = (MediaView) adView.findViewById(R.id.ad_media);
  adView.setMediaView(mediaView);

  // Register the native ad with its ad view.
  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 Compose

@Composable
/** Display a native ad with a user defined template. */
fun DisplayNativeAdView(nativeAd: NativeAd) {
  Box(modifier = Modifier.padding(8.dp)) {
    // Call the NativeAdView composable to display the native ad.
    NativeAdView(nativeAd) {
      Column(modifier = Modifier.fillMaxWidth()) {
        Box {
          Row(modifier = Modifier.fillMaxWidth()) {
            // 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)
                }
              }
            }
          }
          // Display the ad attribution.
          NativeAdAttribution(
            modifier = Modifier.align(Alignment.TopStart),
            text = stringResource(R.string.attribution),
          )
        }

        // Display the media asset.
        NativeAdMediaView(modifier = Modifier.fillMaxWidth())

        // If available, display the body asset.
        nativeAd.body?.let {
          NativeAdBodyView(modifier = Modifier.padding(5.dp)) { Text(text = it) }
        }

        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.
          nativeAd.callToAction?.let { callToAction ->
            NativeAdCallToActionView(Modifier.padding(5.dp)) { NativeAdButton(text = callToAction) }
          }
        }
      }
    }
  }
}

رونهاد AdChoices

کیت توسعه نرم‌افزار یک هم‌پوشانی AdChoices به هر نمای آگهی اضافه می‌کند. در گوشه دلخواه نمای آگهی بومی‌تان فضایی برای نشان‌واره AdChoices که به‌طور خودکار درج می‌شود خالی بگذارید. همچنین، مهم است که AdChoices overlay دیده شود، بنابراین رنگ‌های پس‌زمینه و تصاویر را به‌درستی انتخاب کنید. برای اطلاعات بیشتر درباره ظاهر و عملکرد هم‌پوشانی، به شرح فیلدهای آگهی‌های بومی مراجعه کنید.

ارجاع آگهی

باید اسناد آگهی را نمایش دهید تا مشخص شود که این نما آگهی است. در رهنمودهای خط‌مشی ما اطلاعات بیشتری کسب کنید.

کلیک‌های شناسه مجازی

هیچ گرداننده کلیک سفارشی‌ای را در هیچ نمایی روی یا درون نمای آگهی بومی پیاده‌سازی نکنید. کلیک‌ها روی دارایی‌های نمای آگهی توسط کیت توسعه نرم‌افزار مدیریت می‌شود، به‌شرطی که نماهای دارایی را به‌درستی پر و ثبت کنید.

برای گوش دادن به کلیک‌ها، Google Mobile Ads SDK (Legacy) فراخوانی کلیک را پیاده‌سازی کنید:

جاوا

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()

ImageScaleType

کلاس MediaView هنگام نمایش تصاویر، خصوصیت ImageScaleType دارد. اگر می‌خواهید نحوه مقیاس‌بندی تصویر را در MediaView تغییر دهید، ImageView.ScaleType مربوطه را بااستفاده از روش setImageScaleType() MediaView تنظیم کنید:

جاوا

mediaView.setImageScaleType(ImageView.ScaleType.CENTER_CROP);

Kotlin

mediaView.imageScaleType = ImageView.ScaleType.CENTER_CROP

MediaContent

کلاس MediaContent داده‌های مربوط به محتوای رسانه‌ای آگهی بومی را نگه می‌دارد که بااستفاده از کلاس MediaView نمایش داده می‌شود. وقتی که خصوصیت MediaView mediaContent با نمونه MediaContent تنظیم شده باشد:

  • اگر دارایی ویدیویی دردسترس باشد، میان‌گیری می‌شود و پخش آن در MediaView شروع می‌شود. با بررسی hasVideoContent() می‌توانید متوجه شوید که دارایی ویدیویی دردسترس است یا نه.

  • اگر آگهی حاوی دارایی ویدیویی نباشد، دارایی mainImage بارگیری می‌شود و به‌جای آن در MediaView قرار می‌گیرد.

نابود کردن آگهی

پس‌از نمایش آگهی بومی، آگهی را ازبین ببرید. مثال زیر یک آگهی بومی را ازبین می‌برد:

جاوا

nativeAd.destroy();

Kotlin

nativeAd.destroy()

نمونه‌ها در GitHub

نمونه پیاده‌سازی کامل آگهی‌های بومی:

Java Kotlin JetpackCompose

مراحل بعدی

موضوعات زیر را کاوش کنید: