Crear anuncio de carga de aplicación con Admob en Android

Tiempo de lectura: 3 minutos

Hoy vamos a aprender a crear un anuncio de carga de aplicación con Admob en Android.

Primero implementaremos en nuestro build.gradle:

    implementation 'com.google.android.gms:play-services-ads:23.0.0'

Después tenemos que inicializar los anuncios en nuestro MainActivity:

    MobileAds.initialize(
        this,
        new OnInitializationCompleteListener() {
          @Override
          public void onInitializationComplete(InitializationStatus initializationStatus) {}
        });

Y añadimos en el manifest (debajo de </application>)

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

Y también dentro de <application> </application>

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

Cambia TU_ID_APLICACION_ADMOB por el id de tu APP de Admob.

Ahora vamos a crear un objeto llamado AppOpenManager.java donde pondremos este código:

import static android.provider.Settings.System.getString;

import android.app.Activity;
import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;

import com.cityscaperoommadrid.R;
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.Date;

public class AppOpenAdManager {

    private long loadTime = 0;

    private static final String LOG_TAG = "AppOpenAdManager";
    //Carga el id de la aplicacion de Admob
    private static final String AD_UNIT_ID = "ca-app-pub-3940256099942544/925739592";

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

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


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


    /**
     * Show the ad if one isn't already showing.
     */
    public void showAdIfAvailable(@NonNull final Activity activity,
                                  @NonNull MyApplication.OnShowAdCompleteListener onShowAdCompleteListener) {
        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() {
                        // Set the reference to null so isAdAvailable() returns false.
                        appOpenAd = null;
                        isShowingAd = false;
                        onShowAdCompleteListener.onShowAdComplete();
                        loadAd(activity);
                    }

                    @Override
                    public void onAdFailedToShowFullScreenContent(AdError adError) {
                        // Called when fullscreen content failed to show.
                        Log.d(LOG_TAG, "Ad failed to show.");
                        Log.d(LOG_TAG, adError.getMessage());
                        appOpenAd = null;
                        isShowingAd = false;

                        onShowAdCompleteListener.onShowAdComplete();
                        loadAd(activity);

                    }

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

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


    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 AppOpenAd.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;
                    }
                });
    }

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


}

Una vez creado, tienes que importar tu package en la parte superior: package com.nombre_app.AdsCargarAPP;

Y cambiamos el AdUNIT_ID por el nuestro.

Este es el de prueba: ca-app-pub-3940256099942544/9257395921

Ahora vamos a crear un nuevo objeto llamado MyApplication.java y añadimos:

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

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;
import androidx.lifecycle.ProcessLifecycleOwner;

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 implements Application.ActivityLifecycleCallbacks , LifecycleObserver {

    private AppOpenAdManager appOpenAdManager;
    private Activity currentActivity;


    @Override
    public void onCreate() {
        super.onCreate();
        this.registerActivityLifecycleCallbacks(this);
        MobileAds.initialize(
                this,
                new OnInitializationCompleteListener() {
                    @Override
                    public void onInitializationComplete(InitializationStatus initializationStatus) {
                    }
                });
        ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
        appOpenAdManager = new AppOpenAdManager();
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    protected void onMoveToForeground() {
        // Show the ad (if available) when the app moves to foreground.
        appOpenAdManager.showAdIfAvailable(currentActivity, new OnShowAdCompleteListener() {
            @Override
            public void onShowAdComplete() {
                // Empty because the user will go back to the activity that shows the ad.
            }
        });
    }

    public interface OnShowAdCompleteListener {
        void onShowAdComplete();
    }


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

    @Override
    public void onActivityStarted(Activity activity) {
        // Updating the currentActivity only when an ad is not showing.
        if (!appOpenAdManager.isShowingAd) {
            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) {
    }

}

*Recuerda importar tu package en la parte superior: package com.nombre_app.AdsCargarAPP

Ahora vamos a build.gradle y añadimos:

   def lifecycle_version = "2.3.1"
   implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
   implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"
   annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"

Y finalmente abrimos nuestro AndroidManifest.xml y añadimos dentro de <application

 android:name="com.nombre_app.AdsCargarAPP.MyApplication"

Quedando así:

 <application
        android:name="com.nombre_app.AdsCargarAPP.MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"

Y con esto nos abre el anuncio de carga de APP.

Deja un comentario