marcojak / MauiMTAdmob

MIT License
104 stars 17 forks source link

MTAdmob not initialised #73

Open AboAliElwahy opened 3 months ago

AboAliElwahy commented 3 months ago

i follow all instruction to activate interstitial ad and i use it for android this is my code in main activity using Android.App; using Android.Content.PM; using Android.Gms.Ads; using Android.OS;

namespace pedi_dose_app { [Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)] public class MainActivity : MauiAppCompatActivity { protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); MobileAds.Initialize(this); } } }

my code in android manifest

<?xml version="1.0" encoding="utf-8"?>


my code in main page

public void ShowAd() { string interId = "ca-app-pub-3192508017252023/xxxxxxxxxxx"; if (!CrossMauiMTAdmob.Current.IsInterstitialLoaded()) { CrossMauiMTAdmob.Current.LoadInterstitial(interId); CrossMauiMTAdmob.Current.ShowInterstitial(); } }

when app running this error appear System.Exception: 'MTAdmob not initialised. You need to initilise it by calling CrossMauiMTAdmob.Current.Init in your platform projects!'

ECD10 commented 2 months ago

You can edit like this on MainActivity.cs:

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    MobileAds.Initialize(this);
    CrossMauiMTAdmob.Current.Init(this,"com.your.packagename");
}
marcojak commented 2 months ago

As ECD10, mentioned, you need to call CrossMauiMTAdmob.Current.Init in your native code (both Android and iOS).

Just to notice, the AppId is not the package name but the Admob app id.

Also, don't do:

CrossMauiMTAdmob.Current.LoadInterstitial(interId);
CrossMauiMTAdmob.Current.ShowInterstitial();

The app will not have time to load an interstitial before showing it. You should call LoadInterstitial and then ShowInterstitial at a different time. For example, you could subscribe to the Loaded event and then when ready, call the ShowInterstitial.