تبلیغات باز برنامه

این راهنما برای ناشرانی در نظر گرفته شده است که تبلیغات باز برنامه را با استفاده از Google Mobile Ads SDK (Legacy) ادغام می‌کنند.

App open ads are a special ad format intended for publishers wishing to monetize their app load screens. App open ads can be closed at any time, and are designed to be shown when your users bring your app to the foreground.

تبلیغات باز شدن اپلیکیشن به طور خودکار یک ناحیه کوچک از برند را نشان می‌دهند تا کاربران متوجه شوند که در اپلیکیشن شما هستند. در اینجا مثالی از ظاهر یک تبلیغ باز شدن اپلیکیشن آورده شده است:

پیش‌نیازها

همیشه با تبلیغات آزمایشی تست کنید

هنگام ساخت و آزمایش برنامه‌های خود، مطمئن شوید که از تبلیغات آزمایشی به جای تبلیغات زنده و تولیدی استفاده می‌کنید. عدم انجام این کار می‌تواند منجر به مسدود شدن حساب شما شود.

ساده‌ترین راه برای بارگذاری تبلیغات آزمایشی، استفاده از شناسه واحد تبلیغات آزمایشی اختصاصی ما برای تبلیغات باز برنامه است:

/21775744923/example/app-open

It's been specially configured to return test ads for every request, and you're free to use it in your own apps while coding, testing, and debugging. Just make sure you replace it with your own ad unit ID before publishing your app.

برای اطلاعات بیشتر در مورد نحوه عملکرد تبلیغات آزمایشی Google Mobile Ads SDK (Legacy) ، به فعال کردن تبلیغات آزمایشی مراجعه کنید.

کلاس Application را گسترش دهید

یک کلاس جدید ایجاد کنید که کلاس Application را ارث‌بری کند. این یک روش آگاه از چرخه حیات برای مدیریت تبلیغاتی فراهم می‌کند که به جای یک Activity واحد، به وضعیت برنامه گره خورده‌اند:

جاوا

public class MyApplication extends Application
    implements ActivityLifecycleCallbacks, DefaultLifecycleObserver {

  private AppOpenAdManager appOpenAdManager;
  private Activity currentActivity;

  @Override
  public void onCreate() {
    super.onCreate();
    this.registerActivityLifecycleCallbacks(this);

    ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
    appOpenAdManager = new AppOpenAdManager();
  }

کاتلین

class MyApplication :
  MultiDexApplication(), Application.ActivityLifecycleCallbacks, DefaultLifecycleObserver {

  private lateinit var appOpenAdManager: AppOpenAdManager
  private var currentActivity: Activity? = null

  override fun onCreate() {
    super<MultiDexApplication>.onCreate()
    registerActivityLifecycleCallbacks(this)

    ProcessLifecycleOwner.get().lifecycle.addObserver(this)
    appOpenAdManager = AppOpenAdManager()
  }

سپس، کد زیر را به AndroidManifest.xml خود اضافه کنید:

<!-- TODO: Update to reference your actual package name. -->
<application
    android:name="com.google.android.gms.example.appopendemo.MyApplication" ...>
...
</application>

کامپوننت کاربردی خود را پیاده‌سازی کنید

تبلیغ شما باید به سرعت نمایش داده شود، بنابراین بهتر است قبل از اینکه نیاز به نمایش آن باشد، آن را بارگذاری کنید. به این ترتیب، به محض ورود کاربر به برنامه، تبلیغ آماده نمایش خواهد بود.

یک کامپوننت کاربردی AppOpenAdManager پیاده‌سازی کنید تا کار مربوط به بارگذاری و نمایش تبلیغات App Open را کپسوله‌سازی کند:

جاوا

private class AppOpenAdManager {

  private static final String LOG_TAG = "AppOpenAdManager";
  private static final String AD_UNIT_ID = "/21775744923/example/app-open";

  private AppOpenAd appOpenAd = null;
  private boolean isLoadingAd = false;
  private boolean isShowingAd = false;

  /** Keep track of the time an app open ad is loaded to ensure you don't show an expired ad. */
  private long loadTime = 0;

  /** Constructor. */
  public AppOpenAdManager() {}

کاتلین

private inner class AppOpenAdManager {

  private val googleMobileAdsConsentManager =
  private var appOpenAd: AppOpenAd? = null
  private var isLoadingAd = false
  var isShowingAd = false

  /** Keep track of the time an app open ad is loaded to ensure you don't show an expired ad. */
  private var loadTime: Long = 0

To use the AppOpenAdManager , call the public wrapper methods on the singleton MyApplication instance. The Application class interfaces with the rest of the code, delegating the work of loading and showing the ad to the manager.

بارگذاری یک تبلیغ

مرحله بعدی پر کردن متد loadAd و مدیریت فراخوانی‌های بارگذاری تبلیغات است.

جاوا

AppOpenAd.load(
    context,
    "AD_UNIT_ID",
    new AdManagerAdRequest.Builder().build(),
    new AppOpenAdLoadCallback() {
      @Override
      public void onAdLoaded(AppOpenAd ad) {
        // Called when an app open ad has loaded.
        Log.d(LOG_TAG, "App open ad loaded.");

        appOpenAd = ad;
        isLoadingAd = false;
        loadTime = (new Date()).getTime();
      }

      @Override
      public void onAdFailedToLoad(LoadAdError loadAdError) {
        // Called when an app open ad has failed to load.
        Log.d(LOG_TAG, "App open ad failed to load with error: " + loadAdError.getMessage());

        isLoadingAd = false;
      }
    });

کاتلین

AppOpenAd.load(
  context,
  "AD_UNIT_ID",
  AdManagerAdRequest.Builder().build(),
  object : AppOpenAdLoadCallback() {
    override fun onAdLoaded(ad: AppOpenAd) {
      // Called when an app open ad has loaded.
      Log.d(LOG_TAG, "App open ad loaded.")

      appOpenAd = ad
      isLoadingAd = false
      loadTime = Date().time
    }

    override fun onAdFailedToLoad(loadAdError: LoadAdError) {
      // Called when an app open ad has failed to load.
      Log.d(LOG_TAG, "App open ad failed to load with error: " + loadAdError.message)

      isLoadingAd = false
    }
  },
)

AD_UNIT_ID با شناسه واحد تبلیغاتی خود جایگزین کنید.

نمایش تبلیغ

The most common app open implementation is to attempt to show an app open ad near app launch, start app content if the ad isn't ready, and preload another ad for the next app open opportunity. See App open ad guidance for implementation examples.

کد زیر یک تبلیغ را نمایش داده و متعاقباً آن را بارگذاری مجدد می‌کند:

جاوا

public void showAdIfAvailable(
    @NonNull final Activity activity,
    @NonNull OnShowAdCompleteListener onShowAdCompleteListener) {
  // If the app open ad is already showing, do not show the ad again.
  if (isShowingAd) {
    Log.d(TAG, "The app open ad is already showing.");
    return;
  }

  // If the app open ad is not available yet, invoke the callback then load the ad.
  if (appOpenAd == null) {
    Log.d(TAG, "The app open ad is not ready yet.");
    onShowAdCompleteListener.onShowAdComplete();
    // Load an ad.
    return;
  }

  isShowingAd = true;
  appOpenAd.show(activity);
}

کاتلین

fun showAdIfAvailable(activity: Activity, onShowAdCompleteListener: OnShowAdCompleteListener) {
  // If the app open ad is already showing, do not show the ad again.
  if (isShowingAd) {
    Log.d(TAG, "The app open ad is already showing.")
    return
  }

  // If the app open ad is not available yet, invoke the callback then load the ad.
  if (appOpenAd == null) {
    Log.d(TAG, "The app open ad is not ready yet.")
    onShowAdCompleteListener.onShowAdComplete()
    // Load an ad.
    return
  }

  isShowingAd = true
  appOpenAd?.show(activity)
}

تنظیم FullScreenContentCallback

تابع FullScreenContentCallback رویدادهای مربوط به نمایش AppOpenAd شما را مدیریت می‌کند. قبل از نمایش AppOpenAd ، حتماً تابع callback را تنظیم کنید:

جاوا

appOpenAd.setFullScreenContentCallback(
    new FullScreenContentCallback() {
      @Override
      public void onAdDismissedFullScreenContent() {
        // Called when full screen content is dismissed.
        Log.d(TAG, "Ad dismissed fullscreen content.");
        // Don't forget to set the ad reference to null so you
        // don't show the ad a second time.
        appOpenAd = null;
        isShowingAd = false;

        onShowAdCompleteListener.onShowAdComplete();
        // Load an ad.
      }

      @Override
      public void onAdFailedToShowFullScreenContent(@NonNull AdError adError) {
        // Called when full screen content failed to show.
        Log.d(TAG, adError.getMessage());
        appOpenAd = null;
        // Don't forget to set the ad reference to null so you
        // don't show the ad a second time.
        isShowingAd = false;

        onShowAdCompleteListener.onShowAdComplete();
        // Load an ad.
      }

      @Override
      public void onAdShowedFullScreenContent() {
        Log.d(TAG, "Ad showed fullscreen content.");
      }

      @Override
      public void onAdImpression() {
        // Called when an impression is recorded for an ad.
        Log.d(TAG, "The ad recorded an impression.");
      }

      @Override
      public void onAdClicked() {
        // Called when ad is clicked.
        Log.d(TAG, "The ad was clicked.");
      }
    });

کاتلین

appOpenAd?.fullScreenContentCallback =
  object : FullScreenContentCallback() {
    override fun onAdDismissedFullScreenContent() {
      // Called when full screen content is dismissed.
      Log.d(TAG, "Ad dismissed fullscreen content.")
      // Don't forget to set the ad reference to null so you
      // don't show the ad a second time.
      appOpenAd = null
      isShowingAd = false

      onShowAdCompleteListener.onShowAdComplete()
      // Load an ad.
    }

    override fun onAdFailedToShowFullScreenContent(adError: AdError) {
      // Called when full screen content failed to show.
      Log.d(TAG, adError.message)
      // Don't forget to set the ad reference to null so you
      // don't show the ad a second time.
      appOpenAd = null
      isShowingAd = false

      onShowAdCompleteListener.onShowAdComplete()
      // Load an ad.
    }

    override fun onAdShowedFullScreenContent() {
      Log.d(TAG, "Ad showed fullscreen content.")
    }

    override fun onAdImpression() {
      // Called when an impression is recorded for an ad.
      Log.d(TAG, "The ad recorded an impression.")
    }

    override fun onAdClicked() {
      // Called when ad is clicked.
      Log.d(TAG, "The ad was clicked.")
    }
  }

انقضای تبلیغ را در نظر بگیرید

To make sure you don't show an expired ad, add a method to the AppOpenAdManager that checks how long it has been since your ad reference loaded. Then, use that method to check if the ad is still valid.

جاوا

/** Check if ad was loaded more than n hours ago. */
private boolean wasLoadTimeLessThanNHoursAgo(long numHours) {
  long dateDifference = (new Date()).getTime() - loadTime;
  long numMilliSecondsPerHour = 3600000;
  return (dateDifference < (numMilliSecondsPerHour * numHours));
}

/** Check if ad exists and can be shown. */
private boolean isAdAvailable() {
  // For time interval details, see: https://support.google.com/admob/answer/9341964
  return appOpenAd != null && wasLoadTimeLessThanNHoursAgo(4);
}

کاتلین

/** Check if ad was loaded more than n hours ago. */
private fun wasLoadTimeLessThanNHoursAgo(numHours: Long): Boolean {
  val dateDifference: Long = Date().time - loadTime
  val numMilliSecondsPerHour: Long = 3600000
  return dateDifference < numMilliSecondsPerHour * numHours
}

/** Check if ad exists and can be shown. */
private fun isAdAvailable(): Boolean {
  // For time interval details, see: https://support.google.com/admob/answer/9341964
  return appOpenAd != null && wasLoadTimeLessThanNHoursAgo(4)
}

پیگیری فعالیت‌های فعلی

برای نمایش تبلیغ، به یک زمینه Activity نیاز دارید. برای پیگیری جدیدترین فعالیت مورد استفاده، Application.ActivityLifecycleCallbacks را ثبت و پیاده‌سازی کنید.

جاوا

@Override
public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {}

@Override
public void onActivityStarted(@NonNull Activity activity) {
  // An ad activity is started when an ad is showing, which could be AdActivity class from Google
  // SDK or another activity class implemented by a third party mediation partner. Updating the
  // currentActivity only when an ad is not showing will ensure it is not an ad activity, but the
  // one that shows the ad.
  if (!appOpenAdManager.isShowingAd) {
    currentActivity = activity;
  }
}

@Override
public void onActivityResumed(@NonNull Activity activity) {}

@Override
public void onActivityPaused(@NonNull Activity activity) {}

@Override
public void onActivityStopped(@NonNull Activity activity) {}

@Override
public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {}

@Override
public void onActivityDestroyed(@NonNull Activity activity) {}

کاتلین

override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}

override fun onActivityStarted(activity: Activity) {
  // An ad activity is started when an ad is showing, which could be AdActivity class from Google
  // SDK or another activity class implemented by a third party mediation partner. Updating the
  // currentActivity only when an ad is not showing will ensure it is not an ad activity, but the
  // one that shows the ad.
  if (!appOpenAdManager.isShowingAd) {
    currentActivity = activity
  }
}

override fun onActivityResumed(activity: Activity) {}

override fun onActivityPaused(activity: Activity) {}

override fun onActivityStopped(activity: Activity) {}

override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}

override fun onActivityDestroyed(activity: Activity) {}

registerActivityLifecycleCallbacks lets you listen for all Activity events. By listening for when activities are started and destroyed, you can keep track of a reference to the current Activity , which you then will use in presenting your app open ad.

به رویدادهای برجسته‌سازی برنامه گوش دهید

برای گوش دادن به رویدادهای پیش‌زمینه برنامه، مراحل زیر را انجام دهید:

کتابخانه‌ها را به فایل gradle خود اضافه کنید

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

کاتلین

  dependencies {
    implementation("com.google.android.gms:play-services-ads:25.4.0")
    implementation("androidx.lifecycle:lifecycle-process:2.8.3")
  }

گرووی

  dependencies {
    implementation 'com.google.android.gms:play-services-ads:25.4.0'
    implementation 'androidx.lifecycle:lifecycle-process:2.8.3'
  }

رابط ناظر چرخه عمر را پیاده‌سازی کنید

شما می‌توانید با پیاده‌سازی رابط DefaultLifecycleObserver به رویدادهای پیش‌زمینه‌سازی (foregrounding events) گوش دهید.

تابع onStart() را برای نمایش تبلیغ هنگام باز شدن برنامه پیاده‌سازی کنید.

جاوا

@Override
public void onStart(@NonNull LifecycleOwner owner) {
  DefaultLifecycleObserver.super.onStart(owner);
  appOpenAdManager.showAdIfAvailable(currentActivity);
}

کاتلین

override fun onStart(owner: LifecycleOwner) {
  super.onStart(owner)
  currentActivity?.let {
    // Show the ad (if available) when the app moves to foreground.
    appOpenAdManager.showAdIfAvailable(it)
  }
}

صفحه‌های شروع سرد و بارگیری

The documentation thus far assumes that you only show app open ads when users foreground your app when it is suspended in memory. "Cold starts" occur when your app is launched but was not previously suspended in memory.

یک نمونه از شروع سرد زمانی است که کاربر برای اولین بار برنامه شما را باز می‌کند. با شروع سرد، شما یک تبلیغ باز شده که قبلاً بارگذاری شده باشد و بلافاصله آماده نمایش باشد، نخواهید داشت. تأخیر بین درخواست تبلیغ و دریافت پاسخ تبلیغ می‌تواند وضعیتی را ایجاد کند که کاربران بتوانند قبل از اینکه با یک تبلیغ خارج از متن غافلگیر شوند، به طور خلاصه از برنامه شما استفاده کنند. از این کار اجتناب کنید زیرا یک تجربه کاربری بد است.

The preferred way to use app open ads on cold starts is to use a loading screen to load your game or app assets, and to only show the ad from the loading screen. If your app has completed loading and has sent the user to the main content of your app, don't show the ad.

بهترین شیوه‌ها

App open ads help you monetize your app's loading screen, when the app first launches and during app switches, but it's important to keep best practices in mind so that your users enjoy using your app. It's best to:

  • اولین تبلیغ باز برنامه خود را پس از اینکه کاربران چند بار از برنامه شما استفاده کردند، نمایش دهید.
  • تبلیغات باز شدن برنامه را در زمان‌هایی نمایش دهید که کاربران شما در غیر این صورت منتظر بارگذاری برنامه شما هستند.
  • If you have a loading screen under the app open ad, and your loading screen completes loading before the ad is dismissed, you may want to dismiss your loading screen in the onAdDismissedFullScreenContent() method.

مثال‌ها در گیت‌هاب

مراحل بعدی

مباحث زیر را بررسی کنید: