In this recipe we will leverage our AdMob account and the newly installed package to display some ads in our applications.
In order to complete this recipe, you will have to follow these steps:
components
folder of your solution and click on Get more components.Google Play Services
and add it to your solution.AndroidManifest.xml
file inside the <application>
tag:<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <activity android:name="com.google.android.gms.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />
Android.Gms.Ads
at the top of your MainActivity
class.OnCreate()
method of your MainActivity
class:var adMob = new AdView(this); adMob.AdSize = AdSize.SmartBanner; adMob.AdUnitId = 'Replace this w/ your adUnitId'; var requestbuilder = new AdRequest.Builder(); adMob.LoadAd(requestbuilder.Build()); var layout =FindViewById<LinearLayout>(Resource.Id.mainlayout); layout.AddView(adMob);
First of all, we created a reference to an AdView()
method using the context of the OnCreate()
method:
var adMob = new AdView(this);
Then, we specified that the ad is of the banner type:
adMob.AdSize = AdSize.SmartBanner;
We also had to specify our AdUnitId
using this line of code :
adMob.AdUnitId = 'Replace this w/ your adUnitId';
Finally, we construct, load, and display the banner as follows:
var requestbuilder = new AdRequest.Builder(); adMob.LoadAd(requestbuilder.Build()); var layout = FindViewById<LinearLayout>(Resource.Id.mainlayout); layout.AddView(adMob);
In this recipe, we implement banner ads only. However, AdMob offers the possibility to use the InterstitialAd()
method that we described in the first recipe of this chapter.
In order to integrate one of those on your application, you need to have the following code:
var myInterstitialAd = new InterstitialAd(this); myInterstitialAd.AdUnitId = "Replace this by your id"; var requestbuilder = new AdRequest.Builder(); myInterstitialAd.LoadAd(requestbuilder.Build()); myInterstitialAd.Show()
This works exactly the same as banner except that we use an InterstitialAd
object and not an AdView
object. As the InterstitialAd
object are full screen only, we don't need to specify the size of the ad.
Refer to the following documentation to learn much more about the monetization of your mobile applications and the business model you should choose:
3.135.183.221