AdMob app open ad implementation easy process| AdMob app open ads

 In this tutorial, I will show, How you can easily implement the AdMob app open ad. Recently AdMob add this ad to the AdMob account. Basically, this ad will work when we minimize our app and we return our app then this ad will appear in our app. Most people, use multiple apps at a time. When they use our app with multiple apps and minimize our app. As soon as he returns our app then the ad will show. I think every developer should use this ad. Because this ad definitely increases our income. So I hope this is the best method to increase our earnings.

Now let's come to the point. Basically, this ad is not difficult to implement. But I guide to implement this ad to the new developer. Let's start.

Create a new android studio project and set permission

At first, we have to create a new android studio project. I hope everybody can do to create a project. As our app uses an internet connection so we have to give internet access permission on our app. So give internet and wifi access permission at first. So copy the code below and paste it into the manifest file above the <Application>.

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

AdMob MetaData

 <!-- Sample AdMob app ID: ca-app-pub-3940256099942544~3347511713 -->
        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="ca-app-pub-3940256099942544~3347511713"/>

metadata is very important for an app. Sometimes the app crashes due to metadata. So always add metadata in <application></application>. Copy the code and paste it into <application> tag.

Add AdMob SDK

    def lifecycle_version = "2.0.0"
    implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"
    annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
    implementation 'com.google.android.gms:play-services-ads:20.4.0'

To use AdMob ad we have to add Admob SDK. That's why copy the dependency and paste it build. gradle file under dependency.

Create java class for Admob app open ad

Now we have to create two java classes. The first java class name is AppOpenManager and the second java class name is MyApplication. After creating a java class delete all the code from classes and set it blank. Now you will get too many errors in coding. Don't get panic. It will resolve very soon after we implement coding in the java class.

AppOpenManager java class coding

First, delete all the coding from AppOpenManager java class. And set it totally a blank page. Now copy the code below and paste it on AppOpenManager java class. After implementation, we will get too many errors in our class. Some of our errors resolve when we input classes by typing Alt+Enter from the keyboard. All the errors will resolve when we implement both class's coding.

public class AppOpenManager implements LifecycleObserver, Application.ActivityLifecycleCallbacks{

    private static final String LOG_TAG = "AppOpenManager";
    private static final String AD_UNIT_ID = "ca-app-pub-3940256099942544/3419835294";
    private AppOpenAd appOpenAd = null;
    private long loadTime = 0;
    private AppOpenAd.AppOpenAdLoadCallback loadCallback;
    private Activity currentActivity;
    private final MyApplication myApplication;


    private static boolean isShowingAd = false;

    /** Shows the ad if one isn't already showing. */
    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.setFullScreenContentCallback(fullScreenContentCallback);
            appOpenAd.show(currentActivity);

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

    /** Constructor */
    public AppOpenManager(MyApplication myApplication) {
        this.myApplication = myApplication;
        this.myApplication.registerActivityLifecycleCallbacks(this);
        ProcessLifecycleOwner.get().getLifecycle().addObserver((LifecycleObserver) this);

    }

    /** LifecycleObserver methods */
    @OnLifecycleEvent(ON_START)
    public void onStart() {
        showAdIfAvailable();
        Log.d(LOG_TAG, "onStart");
    }

    /** Request an ad */
    public void fetchAd() {
        // We will implement this below.

        // 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);
    }

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

    /** 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);
    }


    /** ActivityLifecycleCallback methods */
    @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;
    }
}

MyApplication java class coding

Now we have to delete all the code from MyApplication java class and set it a blank page. Copy the below and paste it on MyApplication java class. Input all java classes by clicking Alt+Enter from Keyboard. After doing this all the errors will resolve.

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

Add MyApplication class in Manifest file

android:name="com.techtutorpro.demo.MyApplication"

Add this code into your manifest file under the <Application> tag. Here com.techtutopro.dem is my application package name. Use your own app package name here. Look at the picture.

How to add the AdMob app to open Ad unit?

At first, create an app open ad unit from AdMob. Now go to AppOpenManager java class and find variable

private static final String AD_UNIT_ID = "ca-app-pub-3940256099942544/3419835294";

set your real ad unit here. For the tutorial purpose, I am using a test ad unit here. Always use test ads when you test your coding.


Now run your application. I hope the app runs successfully without any errors. If you like my tutorial don't forget to subscribe to my channel and website. 

Comments

Popular posts from this blog

Facebook audience network bidding code in android studio

Facebook Audience Network ads not showing problem solved