Where should i call MobileAds.initialize()?

孤街醉人 提交于 2020-02-01 03:26:11

问题


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")
    }
    ...
}

回答1:


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.



来源:https://stackoverflow.com/questions/49270255/where-should-i-call-mobileads-initialize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!