Why no ads appear in my application although I write the code correctly?

Viewed 480

I'm trying to add ads to my xamarin android app. I follow videos to do this. But when I finish I found a warning ( 'MobileAds.Initialize(Context, string)' is obsolete: 'deprecated' ), and when trying to start the program the ad not working. I tried most of the solutions but no ads appear in my app.

this is code in the main activity

using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Gms.Ads;

namespace App1.Droid
{
    [Activity(Label = "App1", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize )]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
    protected override void OnCreate(Bundle savedInstanceState)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;
        base.OnCreate(savedInstanceState);
        MobileAds.Initialize(ApplicationContext, "ca-app-pub-3192508017252023~9595491677");
        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
        LoadApplication(new App());
    }
    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
    {
        Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

        base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
}

this is the code of AndroidManifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
android:versionCode="1" android:versionName="1.0" package="com.companyname.app1">
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="28" />
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <application android:label="App1.Android" android:theme="@style/MainTheme">
  <meta-data
      android:name="com.google.android.gms.ads.APPLICATION_ID"
      android:value="ca-app-pub-3192508017252023~9595491677"/>
</application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>

and this is the code o MainPage XAML

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="App1.MainPage"
         xmlns:ads="clr-namespace:App1.Controls">
<StackLayout BackgroundColor="White">
    <RelativeLayout> 
    <Grid RowSpacing="0">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>
    </Grid>
        <StackLayout Grid.Row="0">
            <Label />
            <Button />
        </StackLayout>
    </RelativeLayout>
    <StackLayout HorizontalOptions="EndAndExpand">
        <ads:Ad_control_view BackgroundColor="Red"
                             HorizontalOptions="EndAndExpand"
                             Grid.Row="1"
                             >
            
        </ads:Ad_control_view>
    </StackLayout>
</StackLayout>

this is the class AdmobControl

using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;

namespace App3.Controls
{
    public class AdmobControl :View
{
    public static readonly BindableProperty AdUnitIdProperty = BindableProperty.Create(
               nameof(AdUnitId),
               typeof(string),
               typeof(AdmobControl),
               string.Empty);

    public string AdUnitId
    {
        get => (string)GetValue(AdUnitIdProperty);
        set => SetValue(AdUnitIdProperty, value);
    }
}
} 

this is Ad_control_view

using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;

namespace App1.Controls
{
public class Ad_control_view:View
{
}

}

this is Ad_view_render

using Android.App;
using Android.Content;
using Android.Gms.Ads;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using App1.Controls;
using App1.Droid;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly:ExportRenderer(typeof(Ad_control_view),typeof(Ad_view_render))]
namespace App1.Droid
{
public class Ad_view_render:ViewRenderer<Ad_control_view,AdView>
{
    public Ad_view_render(Context context):base(context)
    {

    }
    string ad_unit_id = "ca-app-pub-3192508017252023/5820253414";
    AdSize ad_size = AdSize.SmartBanner;
    AdView ad_view;
    private AdView Create_Ad_view()
    {
        if (ad_view != null)
            return ad_view;
        ad_view = new AdView(Context)
        {
            AdSize = ad_size,
            AdUnitId = ad_unit_id
        };
        var ad_params = new LinearLayout.LayoutParams(LayoutParams.WrapContent, LayoutParams.WrapContent);
        ad_view.LayoutParameters = ad_params;
        ad_view.LoadAd(new AdRequest.Builder().Build());
        return ad_view;
    }
    protected override void OnElementChanged(ElementChangedEventArgs<Ad_control_view> e)
    {
        base.OnElementChanged(e);
        if (Control==null&& e.NewElement!=null)
        {
            SetNativeControl(Create_Ad_view());
        }

    }
}
}

finally, this is the warning message

Severity Code Description Project File Line Suppression State Warning CS0618 'MobileAds.Initialize(Context, string)' is obsolete: 'deprecated' App1.Android C:\Users\Abo Ali\source\repos\App1\App1\App1.Android\MainActivity.cs 20 Active

enter image description here

2 Answers

With the latest version of AdMob you will initialize things without passing the application ID (that will be pulled from AndroidManifest instead):

base.OnCreate(bundle);
MobileAds.Initialize(this);

I'll be more Accurate with this Answer as of Version 119.1.0 of Xamarin.GooglePlayServices.Ads.Lite of Visual Studio Nuget Packages.

MobileAds.Initialize(AndroidContext, "APP_ID") is Deprecated.

so all you have to do is Delete or comment that line of code and have this line of code in your AndroidManifest.xml

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

All version Prior to this package requires the line of code in the OnCreate Method of the MainActivity Class.

Hope this answer be of help to you!

Related