javaandroidasynchronousadmobinterstitial

how to load interstitial ad without delay when open the Activity


im loading the interstitial ad inside onCreate method then i show it when the user click the button but there's a delay when opening the activity it takes about 2 to 3 seconds to open the activity i tried to load the ad in background but it's not working the error showing is Must be called on the main UI thread

here's the adsmanger class

public class AdsManger {
Context context;
InterstitialAd mInterstitialAd;
AdRequest adRequest;
int adLoadRetry=0;




public AdsManger(Context context) {
    this.context = context;
    triggerAd();

}


public void triggerAd(){

    MobileAds.initialize(context, new OnInitializationCompleteListener() {
        @Override
        public void onInitializationComplete(@NonNull InitializationStatus initializationStatus) {

        }});

    adRequest = new AdRequest.Builder().build();

    InterstitialAd.load(context, "UnitID", adRequest, new InterstitialAdLoadCallback() {
        @Override
        public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
            super.onAdFailedToLoad(loadAdError);
            mInterstitialAd =null;
        
            Toast.makeText(context, "ad loading failed", Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
            super.onAdLoaded(interstitialAd);
            mInterstitialAd=interstitialAd;
          
        }
    });
        

    if(mInterstitialAd==null){
        if(adLoadRetry<3){
            adLoadRetry++;
            triggerAd();
        }
    }}




public void ShowAd(){
    if (mInterstitialAd != null){
        mInterstitialAd.show((Activity) context);
    }
}}

and here's my on create method

@SuppressLint("MissingInflatedId")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_emailwriter);
   
    AdsManger adsManger=new AdsManger(this);

    button=findViewById(R.id.Button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
               adsManger.showAd();});

Solution

  • First of all initialize Ads on app launch, not at the time of when actually you want to show the ad. Then keep ads preloaded so when you want to show ads at that time you'll have the ad ready to show, so it'll be displayed immediately.