Quảng cáo khi mở ứng dụng

Hướng dẫn này dành cho những nhà xuất bản tích hợp quảng cáo khi mở ứng dụng bằng cách sử dụng SDK quảng cáo trên thiết bị di động.

Quảng cáo khi mở ứng dụng là một định dạng quảng cáo đặc biệt dành cho những nhà xuất bản muốn kiếm tiền màn hình tải ứng dụng của họ. Quảng cáo khi mở ứng dụng có thể được thiết kế để đóng bất cứ lúc nào được hiển thị khi người dùng đưa ứng dụng của bạn lên nền trước.

Quảng cáo khi mở ứng dụng tự động hiển thị một vùng nhỏ chứa thương hiệu để người dùng biết rằng họ đang ở ứng dụng của bạn. Sau đây là ví dụ về hình thức của quảng cáo khi mở ứng dụng:

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

Luôn thử nghiệm bằng quảng cáo thử nghiệm

Khi tạo và thử nghiệm ứng dụng, hãy nhớ sử dụng quảng cáo thử nghiệm thay vì quảng cáo thực tế. Chúng tôi có thể tạm ngưng tài khoản của bạn nếu bạn không làm như vậy.

Cách dễ nhất để tải quảng cáo thử nghiệm là sử dụng mã đơn vị quảng cáo thử nghiệm dành riêng cho ứng dụng quảng cáo mở:

ca-app-pub-3940256099942544/9257395921

Mã này được định cấu hình đặc biệt để trả về quảng cáo thử nghiệm cho mọi yêu cầu và bạn sử dụng miễn phí mã này trong ứng dụng của riêng bạn khi lập trình, thử nghiệm và gỡ lỗi. Chỉ cần tạo bạn nhớ thay thế mã này bằng mã đơn vị quảng cáo của riêng mình trước khi xuất bản ứng dụng.

Để biết thêm thông tin về cách hoạt động của quảng cáo thử nghiệm của SDK Quảng cáo của Google trên thiết bị di động, hãy xem Bật quảng cáo thử nghiệm.

Mở rộng lớp Application

Tạo một lớp mới mở rộng lớp Application và thêm lớp sau đây để khởi chạy SDK Quảng cáo của Google trên thiết bị di động khi ứng dụng của bạn khởi động.

Java

/** Application class that initializes, loads and show ads when activities change states. */
public class MyApplication extends Application {

  @Override
  public void onCreate() {
    super.onCreate();
    new Thread(
            () -> {
              // Initialize the Google Mobile Ads SDK on a background thread.
              MobileAds.initialize(this, initializationStatus -> {});
            })
        .start();
  }
}

Kotlin

/** Application class that initializes, loads and show ads when activities change states. */
class MyApplication : Application() {

  override fun onCreate() {
    super.onCreate()
    val backgroundScope = CoroutineScope(Dispatchers.IO)
    backgroundScope.launch {
      // Initialize the Google Mobile Ads SDK on a background thread.
      MobileAds.initialize(this@MyApplication) {}
    }
  }
}

Thao tác này sẽ khởi chạy SDK và cung cấp bộ khung mà bạn sẽ đăng ký sau này cho các sự kiện đưa ứng dụng lên nền trước.

Tiếp theo, hãy thêm mã sau vào AndroidManifest.xml của bạn:

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

Triển khai thành phần tiện ích

Quảng cáo của bạn phải nhanh chóng hiển thị, vì vậy, tốt nhất bạn nên tải quảng cáo trước khi cần hiển thị màn hình. Bằng cách đó, bạn sẽ có quảng cáo sẵn sàng chạy ngay khi người dùng của bạn nhập vào ứng dụng của bạn.

Triển khai thành phần tiện ích AppOpenAdManager để thực hiện các yêu cầu quảng cáo trước khi bạn cần hiển thị quảng cáo.

Java

public class MyApplication extends Application {
  // ...
  /** Inner class that loads and shows app open ads. */
  private class AppOpenAdManager {
    private static final String LOG_TAG = "AppOpenAdManager";
    private static final String AD_UNIT_ID = "ca-app-pub-3940256099942544/9257395921";

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

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

    /** Request an ad. */
    private void loadAd(Context context) {
      // We will implement this later.
    }

    /** Check if ad exists and can be shown. */
    private boolean isAdAvailable() {
      return appOpenAd != null;
    }
  }
}

Kotlin

private const val String LOG_TAG = "AppOpenAdManager"
private const val String AD_UNIT_ID = "ca-app-pub-3940256099942544/9257395921"

public class MyApplication extends Application {
  // ...
  /** Inner class that loads and shows app open ads. */
  private inner class AppOpenAdManager {
    private var appOpenAd: AppOpenAd? = null
    private var isLoadingAd = false
    var isShowingAd = false

    /** Request an ad. */
    fun loadAd(context: Context) {
      // We will implement this later.
    }

    /** Check if ad exists and can be shown. */
    private fun isAdAvailable(): Boolean {
      return appOpenAd != null
    }
  }
}

Giờ đây khi đã có một lớp tiện ích, bạn có thể tạo thực thể cho lớp này trong Lớp MyApplication:

Java

public class MyApplication extends Application {

  private AppOpenAdManager appOpenAdManager;

  @Override
  public void onCreate() {
    super.onCreate();
    new Thread(
            () -> {
              // Initialize the Google Mobile Ads SDK on a background thread.
              MobileAds.initialize(this, initializationStatus -> {});
            })
        .start();
    appOpenAdManager = new AppOpenAdManager(this);
  }
}

Kotlin

class MyApplication : Application() {

  private lateinit var appOpenAdManager: AppOpenAdManager

  override fun onCreate() {
    super.onCreate()
    val backgroundScope = CoroutineScope(Dispatchers.IO)
    backgroundScope.launch {
      // Initialize the Google Mobile Ads SDK on a background thread.
      MobileAds.initialize(this@MyApplication) {}
    }
    appOpenAdManager = AppOpenAdManager()
  }
}

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

Bước tiếp theo là điền vào phương thức loadAd() và xử lý lượt tải quảng cáo lệnh gọi lại.

Java

private class AppOpenAdManager {
  // ...
  /** Request an ad. */
  public void loadAd(Context context) {
    // Do not load ad if there is an unused ad or one is already loading.
    if (isLoadingAd || isAdAvailable()) {
      return;
    }

    isLoadingAd = true;
    AdRequest request = new AdRequest.Builder().build();
    AppOpenAd.load(
        context, AD_UNIT_ID, request,
        AppOpenAd.APP_OPEN_AD_ORIENTATION_PORTRAIT,
        new AppOpenAdLoadCallback() {
          @Override
          public void onAdLoaded(AppOpenAd ad) {
            // Called when an app open ad has loaded.
            Log.d(LOG_TAG, "Ad was 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, loadAdError.getMessage());
            isLoadingAd = false;
          }
        });
  }
  // ...
}

Kotlin

private inner class AppOpenAdManager {
  // ...
  /** Request an ad. */
  fun loadAd(context: Context) {
    // Do not load ad if there is an unused ad or one is already loading.
    if (isLoadingAd || isAdAvailable()) {
      return
    }

    isLoadingAd = true
    val request = AdRequest.Builder().build()
    AppOpenAd.load(
        context, AD_UNIT_ID, request,
        AppOpenAd.APP_OPEN_AD_ORIENTATION_PORTRAIT,
        object : AppOpenAdLoadCallback() {

          override fun onAdLoaded(ad: AppOpenAd) {
            // Called when an app open ad has loaded.
            Log.d(LOG_TAG, "Ad was 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, loadAdError.message)
            isLoadingAd = false;
          }
        })
  }
  // ...
}

Hiển thị quảng cáo và xử lý các sự kiện gọi lại toàn màn hình

Cách triển khai quảng cáo khi mở ứng dụng phổ biến nhất là cố gắng hiển thị một quảng cáo khi mở ứng dụng gần khởi chạy ứng dụng, bắt đầu nội dung ứng dụng nếu quảng cáo chưa sẵn sàng và tải trước một quảng cáo khác cho cơ hội tiếp theo khi mở ứng dụng. Xem Hướng dẫn về quảng cáo khi mở ứng dụng để biết các ví dụ về cách triển khai.

Mã sau đây minh hoạ cách hiển thị và sau đó tải lại quảng cáo:

Java

public class MyApplication extends Application {
  // ...
  /** Interface definition for a callback to be invoked when an app open ad is complete. */
  public interface OnShowAdCompleteListener {
    void onShowAdComplete();
  }

  private class AppOpenAdManager {
    // ...

    /** Shows the ad if one isn't already showing. */
    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(LOG_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 (!isAdAvailable()) {
        Log.d(LOG_TAG, "The app open ad is not ready yet.");
        onShowAdCompleteListener.onShowAdComplete();
        loadAd(activity);
        return;
      }

      appOpenAd.setFullScreenContentCallback(
          new FullScreenContentCallback() {

            @Override
            public void onAdDismissedFullScreenContent() {
              // Called when fullscreen content is dismissed.
              // Set the reference to null so isAdAvailable() returns false.
              Log.d(LOG_TAG, "Ad dismissed fullscreen content.");
              appOpenAd = null;
              isShowingAd = false;

              onShowAdCompleteListener.onShowAdComplete();
              loadAd(activity);
            }

            @Override
            public void onAdFailedToShowFullScreenContent(AdError adError) {
              // Called when fullscreen content failed to show.
              // Set the reference to null so isAdAvailable() returns false.
              Log.d(LOG_TAG, adError.getMessage());
              appOpenAd = null;
              isShowingAd = false;

              onShowAdCompleteListener.onShowAdComplete();
              loadAd(activity);
            }

            @Override
            public void onAdShowedFullScreenContent() {
              // Called when fullscreen content is shown.
              Log.d(LOG_TAG, "Ad showed fullscreen content.");
            }
          });
      isShowingAd = true;
      appOpenAd.show(activity);
    }
    // ...
  }
}

Kotlin

class MyApplication : Application() {
  // ...
  /** Interface definition for a callback to be invoked when an app open ad is complete. */
  interface OnShowAdCompleteListener {
    fun onShowAdComplete()
  }

  private inner class AppOpenAdManager {
    // ...

    /** Shows the ad if one isn't already showing. */
    fun showAdIfAvailable(
        activity: Activity,
        onShowAdCompleteListener: OnShowAdCompleteListener) {
      // If the app open ad is already showing, do not show the ad again.
      if (isShowingAd) {
        Log.d(LOG_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 (!isAdAvailable()) {
        Log.d(LOG_TAG, "The app open ad is not ready yet.")
        onShowAdCompleteListener.onShowAdComplete()
        loadAd(activity)
        return
      }

      appOpenAd?.setFullScreenContentCallback(
          object : FullScreenContentCallback() {

            override fun onAdDismissedFullScreenContent() {
              // Called when full screen content is dismissed.
              // Set the reference to null so isAdAvailable() returns false.
              Log.d(LOG_TAG, "Ad dismissed fullscreen content.")
              appOpenAd = null
              isShowingAd = false

              onShowAdCompleteListener.onShowAdComplete()
              loadAd(activity)
            }

            override fun onAdFailedToShowFullScreenContent(adError: AdError) {
              // Called when fullscreen content failed to show.
              // Set the reference to null so isAdAvailable() returns false.
              Log.d(LOG_TAG, adError.message)
              appOpenAd = null
              isShowingAd = false

              onShowAdCompleteListener.onShowAdComplete()
              loadAd(activity)
            }

            override fun onAdShowedFullScreenContent() {
              // Called when fullscreen content is shown.
              Log.d(LOG_TAG, "Ad showed fullscreen content.")
            }
          })
      isShowingAd = true
      appOpenAd?.show(activity)
    }
    // ...
  }
}

Chiến lược phát hành đĩa đơn FullScreenContentCallback xử lý các sự kiện như khi quảng cáo được hiển thị, không thể hiển thị hoặc khi quảng cáo đã loại bỏ.

Xem xét thời hạn của quảng cáo

Để đảm bảo bạn không hiển thị quảng cáo đã hết hạn, hãy thêm một phương thức vào AppOpenAdManager để kiểm tra xem đã bao lâu kể từ khi tệp đối chiếu quảng cáo của bạn được tải. Sau đó, hãy sử dụng để kiểm tra xem quảng cáo có còn hợp lệ hay không.

Java

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

  // ...

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

  /** Check if ad exists and can be shown. */
  public boolean isAdAvailable() {
    return appOpenAd != null && wasLoadTimeLessThanNHoursAgo(4);
  }
}

Kotlin

private inner class AppOpenAdManager {
  // ...
  /** 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;

  // ...

  /** Utility method to 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 {
    return appOpenAd != null && wasLoadTimeLessThanNHoursAgo(4)
  }
}

Theo dõi hoạt động hiện tại

Để hiển thị quảng cáo, bạn cần có ngữ cảnh Activity. Để theo dõi nhiều thông tin nhất hoạt động hiện tại đang được sử dụng, đăng ký và triển khai Application.ActivityLifecycleCallbacks.

Java

public class MyApplication extends Application implements ActivityLifecycleCallbacks {

  private Activity currentActivity;

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

  /** ActivityLifecycleCallback methods. */
  @Override
  public void onActivityCreated(Activity activity, Bundle savedInstanceState) {}

  @Override
  public void onActivityStarted(Activity activity) {
    currentActivity = activity
  }

  @Override
  public void onActivityResumed(Activity activity) {}

  @Override
  public void onActivityStopped(Activity activity) {}

  @Override
  public void onActivityPaused(Activity activity) {}

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

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

Kotlin

class MyApplication : Application(), Application.ActivityLifecycleCallbacks {

  private var currentActivity: Activity? = null

  override fun onCreate() {
    super.onCreate()
    registerActivityLifecycleCallbacks(this)
    // ...
  }

  /** ActivityLifecycleCallback methods. */
  override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}

  override fun onActivityStarted(activity: Activity) {
    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 cho phép bạn nghe tất cả sự kiện Activity. Bằng cách lắng nghe thời điểm hoạt động đã được bắt đầu và bị huỷ, bạn có thể theo dõi tham chiếu đến Activity mà sau đó bạn sẽ sử dụng để hiển thị quảng cáo khi mở ứng dụng.

Theo dõi các sự kiện đưa ứng dụng lên nền trước

Thêm thư viện vào tệp gradle của bạn

Để nhận thông báo về các sự kiện đưa ứng dụng lên nền trước, bạn cần đăng ký một DefaultLifecycleObserver. Thêm phần phụ thuộc vào tệp bản dựng cấp ứng dụng:

Kotlin

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

Groovy

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

Triển khai giao diện trình quan sát vòng đời

Bạn có thể theo dõi các sự kiện đưa lên nền trước bằng cách triển khai Giao diện DefaultLifecycleObserver.

Triển khai sự kiện onStart để hiển thị quảng cáo khi mở ứng dụng.

Java

public class MyApplication extends Application
    implements ActivityLifecycleCallbacks, LifecycleObserver {
  // ...
  @Override
  public void onCreate() {
    super.onCreate();
    this.registerActivityLifecycleCallbacks(this);
    new Thread(
            () -> {
              // Initialize the Google Mobile Ads SDK on a background thread.
              MobileAds.initialize(this, initializationStatus -> {});
            })
        .start();
    ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
    appOpenAdManager = new AppOpenAdManager();
  }

  /** LifecycleObserver method that shows the app open ad when the app moves to foreground. */
  @OnLifecycleEvent(Event.ON_START)
  protected void onMoveToForeground() {
    // Show the ad (if available) when the app moves to foreground.
    appOpenAdManager.showAdIfAvailable(currentActivity);
  }

  /** Show the ad if one isn't already showing. */
  private void showAdIfAvailable(@NonNull final Activity activity) {
      showAdIfAvailable(
          activity,
          new OnShowAdCompleteListener() {
            @Override
            public void onShowAdComplete() {
              // Empty because the user will go back to the activity that shows the ad.
            }
          });
  }
}

Kotlin

class MyApplication : Application(),
    Application.ActivityLifecycleCallbacks, LifecycleObserver {
  // ...
  override fun onCreate() {
    super.onCreate()
    registerActivityLifecycleCallbacks(this)
    val backgroundScope = CoroutineScope(Dispatchers.IO)
    backgroundScope.launch {
      // Initialize the Google Mobile Ads SDK on a background thread.
      MobileAds.initialize(this@MyApplication) {}
    }
    ProcessLifecycleOwner.get().lifecycle.addObserver(this)
    appOpenAdManager = AppOpenAdManager()
  }

  /** LifecycleObserver method that shows the app open ad when the app moves to foreground. */
  @OnLifecycleEvent(Lifecycle.Event.ON_START)
  fun onMoveToForeground() {
    // Show the ad (if available) when the app moves to foreground.
    currentActivity?.let {
      appOpenAdManager.showAdIfAvailable(it)
    }
  }

  /** Show the ad if one isn't already showing. */
  fun showAdIfAvailable(activity: Activity) {
    showAdIfAvailable(
        activity,
        object : OnShowAdCompleteListener {
          override fun onShowAdComplete() {
            // Empty because the user will go back to the activity that shows the ad.
          }
        })
  }
}

Khởi động nguội và màn hình tải

Cho đến nay, tài liệu này giả định rằng bạn chỉ hiển thị quảng cáo khi mở ứng dụng khi người dùng chạy ứng dụng trên nền trước khi ứng dụng bị tạm ngưng trong bộ nhớ. "Khởi động nguội" xảy ra khi ứng dụng của bạn đã được khởi chạy nhưng trước đó không bị tạm ngưng trong bộ nhớ.

Một ví dụ về khởi động nguội là khi người dùng mở ứng dụng lần đầu tiên. Trong trường hợp khởi động nguội, bạn sẽ không có quảng cáo khi mở ứng dụng đã tải trước đó sẵn sàng được hiển thị ngay lập tức. Độ trễ giữa thời điểm bạn yêu cầu quảng cáo và nhận được quảng cáo có thể tạo ra một tình huống trong đó người dùng có thể sử dụng ngay ứng dụng của bạn trước khi bị bất ngờ bởi quảng cáo không phù hợp. Bạn nên tránh điều này vì đây là trải nghiệm người dùng kém.

Cách ưu tiên để sử dụng quảng cáo khi mở ứng dụng khi khởi động nguội là dùng màn hình tải để tải nội dung trò chơi hoặc ứng dụng của bạn và chỉ hiển thị quảng cáo khi tải màn hình. Nếu ứng dụng của bạn đã tải xong và đã đưa người dùng đến nội dung của ứng dụng, đừng hiển thị quảng cáo.

Các phương pháp hay nhất

Quảng cáo khi mở ứng dụng giúp bạn kiếm tiền từ màn hình tải của ứng dụng (khi ứng dụng xuất hiện lần đầu tiên) và trong quá trình chuyển đổi ứng dụng, nhưng điều quan trọng là phải duy trì các phương pháp hay nhất về để người dùng thích sử dụng ứng dụng của bạn. Tốt nhất là bạn nên:

  • Hiển thị quảng cáo khi mở ứng dụng đầu tiên sau khi người dùng đã sử dụng ứng dụng của bạn vài lần.
  • Hiển thị quảng cáo khi mở ứng dụng trong những khoảng thời gian mà người dùng đáng lẽ phải chờ đợi để tải ứng dụng.
  • Nếu bạn có màn hình tải trong quảng cáo khi mở ứng dụng và màn hình tải tải xong trước khi quảng cáo bị đóng, bạn nên đóng màn hình tải trong phương thức onAdDismissedFullScreenContent().

Ví dụ trên GitHub

  • Ví dụ về Quảng cáo khi mở ứng dụng: Java | Kotlin

Các bước tiếp theo

Khám phá các chủ đề sau: