Here is the simplest way of how to integrate admob in android using kotlin and firebase is very easy.
1. Create a android project in android studio
2. go to tools->Firebase and go to bottom admob details and click first option connect your app to firebase and if you successfully connected then following green ok button appears.
Now click add a banner ad to you app
3. Now click 2nd option ad admob to your app then you got following dialog box and click accept for changes.
and
4. To put a banner ad in your app, add the following code to your layout file, including the Android Ads schema.
5. Now, you have to load the ad in the activity
Add code to the onCreate() class of this activity to load the ad.
// appId, you can find through the ad mob
MobileAds.initialize(this, resources.getString(R.string.app_id)); // bannar addval adRequest = AdRequest.Builder().build()adView.loadAd(adRequest)
don't forget to import:
import kotlinx.android.synthetic.main.activity_main.*
6. you have to create ad unit from admob.com and add on string.xml, that has name banner_ad_unit_id.If you want to add Interstitial Ad, then do following steps,
First you have create Interstitial ad unit in admob and save interstitial_ad_unit_id string.xml.
Inside the MainActivity.
internal lateinit var mInterstitialAd: InterstitialAd internal lateinit var adRequest : AdRequest
want the onCreate method:
Create function requestNewInterstitial(),mInterstitialAd = InterstitialAd(this) mInterstitialAd.setAdUnitId(getString(R.string.interstitial_ad_unit_id)); requestNewInterstitial()
private fun requestNewInterstitial() { adRequest = AdRequest.Builder().build() mInterstitialAd.loadAd(adRequest) }
Don't forget to internet permission, otherwise you ad will not displayed in your app.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Finally, Inside the button click
if (mInterstitialAd.isLoaded()) { mInterstitialAd.show(); } else { //go to second activity or do something } mInterstitialAd.adListener = object : AdListener() { override fun onAdClosed() { requestNewInterstitial() //go to second activity or do something } override fun onAdLoaded() { } override fun onAdFailedToLoad(i: Int) { Log.w("AgeActivity", "onAdFailedToLoad:" + i) } }
Now your both banner ad and Interstitial Ad both will be displayed , just like screenshot below.
Download and fork project.
#HappyCoding!! and #ILoveKotlin