Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should i call MobileAds.initialize()?

I have read https://developers.google.com/admob/android/quick-start?hl=en-US#import_the_mobile_ads_sdk

I need to initialize MobileAds using Code A in order to display AdMob AD.

I have some activities which need to display ADs, do I need to add code A in my all activities?

And more, why can the AdMob Ad be displayed correctly even if I remove

MobileAds.initialize(this, "YOUR_ADMOB_APP_ID")

Code A

import com.google.android.gms.ads.MobileAds;

class MainActivity : AppCompatActivity() {
    ...
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Sample AdMob app ID: ca-app-pub-3940256099942544~3347511713
        MobileAds.initialize(this, "YOUR_ADMOB_APP_ID")
    }
    ...
}
like image 420
HelloCW Avatar asked Mar 14 '18 05:03

HelloCW


2 Answers

From the docs of MobileAds.initialize():

This method should be called as early as possible, and only once per application launch.

The proper way to do this would be to call it in the onCreate() method of the Application class.

If you don't have an Application class, simply create one, something like this:

class YourApp: Application() {

    override fun onCreate() {
        super.onCreate()
        MobileAds.initialize(this, "YOUR_ADMOB_APP_ID")
    }
}

You have to reference this class in AndroidManifest.xml, by setting the android:name attribute of the application tag:

<application
    android:name=".YourApp"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">

    <!-- ... -->

</application>

And regarding your question:

why can the AdMob Ad be displayed correctly even if I remove

MobileAds.initialize(this, "YOUR_ADMOB_APP_ID")

Quote from Veer Arjun Busani of the Mobile Ads SDK team:

The Mobile Ads SDK take a few milliseconds to initialize itself and we now have provided this method to call it way before you even call your first ad. Once that is done, there would not be any added load time for your first request. If you do not call this, then your very first AdRequest would take a few milliseconds more as it first needs to initialize itself.

So basically if you do not call MobileAds.initialize(), then the first AdRequest will call it implicitly.

like image 183
earthw0rmjim Avatar answered Oct 19 '22 10:10

earthw0rmjim


MobileAds.initialize(this, "YOUR-APP-ID") has deprecated. Use the below code instead.

import android.app.Application
import com.google.android.gms.ads.MobileAds

class MyApp: Application() {

   override fun onCreate() {
       MobileAds.initialize(applicationContext)
       super.onCreate()
   }

}
like image 1
ray1195 Avatar answered Oct 19 '22 11:10

ray1195