Crear un anuncio de carga de aplicación en Android Java/Kotlin

Tiempo de lectura: 5 minutos

Os traigo este tutorial para crear un anuncio de carga de aplicación con Android usando Java o Kotlin.

1. Configuración de AdMob:

  • Ve al sitio web de AdMob y crea una cuenta si aún no tienes una.
  • Crea un nuevo anuncio de tipo «Pantalla de inicio» en AdMob.
  • Deberás copiar el código de aplicación y código de anuncio.
  • Te recomiendo que los guardes como String de Android.

2. Integración de la biblioteca de AdMob en tu proyecto:

Agrega las siguientes dependencias en tu archivo build.gradle para incorporar la biblioteca de AdMob.

dependencies {
    implementation 'com.google.android.gms:play-services-ads:22.5.0'
}

3. Actualizar el archivo AndroidManifest.xml:

Agrega el siguiente permiso y la configuración de meta-datos para AdMob en tu archivo AndroidManifest.xml.

<uses-permission android:name="android.permission.INTERNET" />

<meta-data
    android:name="com.google.android.gms.ads.APPLICATION_ID"
    android:value="TU_APP_ID_DE_ADMOB" />

Reemplaza «TU_APP_ID_DE_ADMOB» con el ID de aplicación proporcionado por AdMob.

*Te recomiendo que guardes el código dentro de los Strings de Android en res > values > strings > strings.xml

<string name="ads_app" translatable="false">ca-app-pub-3940256099942544~3347511713</string>

Para cargarlo tendrás que poner lo siguiente:

        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="@string/ads_app" />

4. Ahora vamos a crear los objetos necesasarios para crear una pantalla de carga de APP

Me gusta crearlos dentro de util/ads, creamos ese paquete y añadimos el siguiente fichero:

Java

MyApplication.java

import android.app.Application;

import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;

public class MyApplication extends Application {
    private static AppOpenManager appOpenManager;

    @Override
    public void onCreate() {
        super.onCreate();
        MobileAds.initialize(
                this,
                new OnInitializationCompleteListener() {
                    @Override
                    public void onInitializationComplete(InitializationStatus initializationStatus) {
                    }
                });
        appOpenManager = new AppOpenManager(this);
    }
}

Con esto inicializamos los anuncios.

Kotlin

MyApplication.kt

package com.app.fuentes_de_agua.Util.AdsCargarAPP

import android.app.Application
import com.google.android.gms.ads.MobileAds
import com.google.android.gms.ads.initialization.InitializationStatus
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener

class MyApplication : Application() {
    companion object {
        lateinit var appOpenManager: AppOpenManager
            private set
    }

    override fun onCreate() {
        super.onCreate()
        MobileAds.initialize(
            this,
            OnInitializationCompleteListener { initializationStatus -> })
        appOpenManager = AppOpenManager(this)
    }
}

Ahora vamos a crear la clase llamada AppOpenManager

Java

AppOpenManager.java

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.util.Log;

import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;
import androidx.lifecycle.ProcessLifecycleOwner;

import com.google.android.gms.ads.AdError;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.FullScreenContentCallback;
import com.google.android.gms.ads.LoadAdError;

import java.util.Date;

import static androidx.lifecycle.Lifecycle.Event.ON_START;

public class AppOpenManager implements LifecycleObserver, Application.ActivityLifecycleCallbacks {

    private Activity currentActivity;
    private static boolean isShowingAd = false;
    private long loadTime = 0;

    private static final String LOG_TAG = "AppOpenManager";
    private static String AD_UNIT_ID = "";
    private AppOpenAd appOpenAd = null;

    private AppOpenAd.AppOpenAdLoadCallback loadCallback;

    private final MyApplication myApplication;

    /**
     * Constructor
     */
    public AppOpenManager(MyApplication myApplication) {
        this.myApplication = myApplication;
        AD_UNIT_ID = myApplication.getResources().getString(R.string.ads_carga);
        this.myApplication.registerActivityLifecycleCallbacks(this);
        ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
    }

    /**
     * Request an ad
     */

    /**
     * Creates and returns ad request.
     */
    private AdRequest getAdRequest() {
        return new AdRequest.Builder().build();
    }

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

    private boolean wasLoadTimeLessThanNHoursAgo(long numHours) {
        long dateDifference = (new Date()).getTime() - this.loadTime;
        long numMilliSecondsPerHour = 3600000;
        return (dateDifference < (numMilliSecondsPerHour * numHours));
    }


    /**
     * Request an ad
     */
    public void fetchAd() {
        // Have unused ad, no need to fetch another.
        if (isAdAvailable()) {
            return;
        }

        loadCallback =
                new AppOpenAd.AppOpenAdLoadCallback() {
                    /**
                     * Called when an app open ad has loaded.
                     *
                     * @param ad the loaded app open ad.
                     */
                    @Override
                    public void onAdLoaded(AppOpenAd ad) {
                        AppOpenManager.this.appOpenAd = ad;
                        AppOpenManager.this.loadTime = (new Date()).getTime();

                    }

                    /**
                     * Called when an app open ad has failed to load.
                     *
                     * @param loadAdError the error.
                     */
                    @Override
                    public void onAdFailedToLoad(LoadAdError loadAdError) {
                        // Handle the error.
                    }

                };
        AdRequest request = getAdRequest();
        AppOpenAd.load(
                myApplication, AD_UNIT_ID, request,
                AppOpenAd.APP_OPEN_AD_ORIENTATION_PORTRAIT, loadCallback);
    }

    public void showAdIfAvailable() {
        // Only show ad if there is not already an app open ad currently showing
        // and an ad is available.
        if (!isShowingAd && isAdAvailable()) {
            Log.d(LOG_TAG, "Will show ad.");

            FullScreenContentCallback fullScreenContentCallback =
                    new FullScreenContentCallback() {
                        @Override
                        public void onAdDismissedFullScreenContent() {
                            // Set the reference to null so isAdAvailable() returns false.
                            AppOpenManager.this.appOpenAd = null;
                            isShowingAd = false;
                            fetchAd();
                        }

                        @Override
                        public void onAdFailedToShowFullScreenContent(AdError adError) {
                        }

                        @Override
                        public void onAdShowedFullScreenContent() {
                         
                            isShowingAd = true;
                        }
                    };

            appOpenAd.show(currentActivity);

        } else {
            Log.d(LOG_TAG, "Can not show ad.");
            fetchAd();
        }
    }


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

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

    @Override
    public void onActivityResumed(Activity activity) {
        currentActivity = 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) {
        currentActivity = null;
    }

    /**
     * LifecycleObserver methods
     */
    @OnLifecycleEvent(ON_START)
    public void onStart() {
            showAdIfAvailable();
    }
}

Recuerda cambiar la línea de AD_UNIT_ID = myApplication.getResources().getString(R.string.ads_carga); por el id de tu anuncio:

 <string name="ads_carga" translatable="false">ca-app-pub-3940256099942544/3419835294</string>

Kotlin

AppOpenManager.kt

import android.app.Activity
import android.app.Application
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.lifecycle.ProcessLifecycleOwner
import com.google.android.gms.ads.AdError
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.FullScreenContentCallback
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.appopen.AppOpenAd
import java.util.*

class AppOpenManager(private val myApplication: MyApplication) : LifecycleObserver, Application.ActivityLifecycleCallbacks {

    private var currentActivity: Activity? = null
    private var isShowingAd = false
    private var loadTime: Long = 0

    private val LOG_TAG = "AppOpenManager"
    private var AD_UNIT_ID = ""
    private var appOpenAd: AppOpenAd? = null

    private var loadCallback: AppOpenAd.AppOpenAdLoadCallback? = null

    /**
     * Constructor
     */
    init {
        AD_UNIT_ID = myApplication.resources.getString(R.string.ads_carga)
        myApplication.registerActivityLifecycleCallbacks(this)
        ProcessLifecycleOwner.get().lifecycle.addObserver(this)
    }

    /**
     * Request an ad
     */

    /**
     * Creates and returns ad request.
     */
    private fun getAdRequest(): AdRequest {
        return AdRequest.Builder().build()
    }

    /**
     * Utility method that checks if ad exists and can be shown.
     */
    fun isAdAvailable(): Boolean {
        return appOpenAd != null && wasLoadTimeLessThanNHoursAgo(4)
    }

    private fun wasLoadTimeLessThanNHoursAgo(numHours: Long): Boolean {
        val dateDifference = Date().time - loadTime
        val numMilliSecondsPerHour = 3600000
        return dateDifference < numMilliSecondsPerHour * numHours
    }

    /**
     * Request an ad
     */
    fun fetchAd() {
        // Have unused ad, no need to fetch another.
        if (isAdAvailable()) {
            return
        }

        loadCallback =
            object : AppOpenAd.AppOpenAdLoadCallback() {
                /**
                 * Called when an app open ad has loaded.
                 *
                 * @param ad the loaded app open ad.
                 */
                override fun onAdLoaded(ad: AppOpenAd) {
                    appOpenAd = ad
                    loadTime = Date().time
                }

                /**
                 * Called when an app open ad has failed to load.
                 *
                 * @param loadAdError the error.
                 */
                override fun onAdFailedToLoad(loadAdError: LoadAdError) {
                    // Handle the error.
                }

            }
        val request = getAdRequest()
        AppOpenAd.load(
            myApplication, AD_UNIT_ID, request,
            AppOpenAd.APP_OPEN_AD_ORIENTATION_PORTRAIT, loadCallback!!
        )
    }

    fun showAdIfAvailable() {
        // Only show ad if there is not already an app open ad currently showing
        // and an ad is available.
        if (!isShowingAd && isAdAvailable()) {
            Log.d(LOG_TAG, "Will show ad.")

            val fullScreenContentCallback: FullScreenContentCallback =
                object : FullScreenContentCallback() {
                    override fun onAdDismissedFullScreenContent() {
                        // Set the reference to null so isAdAvailable() returns false.
                        appOpenAd = null
                        isShowingAd = false
                        fetchAd()
                    }

                    override fun onAdFailedToShowFullScreenContent(adError: AdError) {}

                    override fun onAdShowedFullScreenContent() {
                        isShowingAd = true
                    }
                }

            appOpenAd?.show(currentActivity!!, fullScreenContentCallback)

        } else {
            Log.d(LOG_TAG, "Can not show ad.")
            fetchAd()
        }
    }

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

    override fun onActivityStarted(activity: Activity) {
        currentActivity = activity
    }

    override fun onActivityResumed(activity: Activity) {
        currentActivity = activity
    }

    override fun onActivityStopped(activity: Activity) {}

    override fun onActivityPaused(activity: Activity) {}

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

    override fun onActivityDestroyed(activity: Activity) {
        currentActivity = null
    }

    /**
     * LifecycleObserver methods
     */
    @OnLifecycleEvent(

Recuerda cambiar la línea de

    AD_UNIT_ID = myApplication.resources.getString(R.string.ads_carga)

por el id de tu anuncio:

 <string name="ads_carga" translatable="false">ca-app-pub-3940256099942544/3419835294</string>

Ya tenemos todo listo para que se pueda utilizar.

5. Indicamos que cargue el contexto del anuncio desde AndroidManifest.xml:

Ve a tu AndroidManifest.xml y actualiza la parte de <application android:name="" con el siguiente código:

   <application
        android:name=".Util.ads.MyApplication"

De esta forma cargará los anuncios cuando abramos la app (desde segundo plano):

Datos de prueba de anuncios:

Recomiendo utiliza estos datos de prueba para programar los anuncios, antes de publicarlos (recuerda cambiar a los originales al publicar):

<string name="ads_app" translatable="false">ca-app-pub-3940256099942544~3347511713</string>
<string name="ads_carga" translatable="false">ca-app-pub-3940256099942544/3419835294</string>

Deja un comentario