In this blog, we must create an interstitial ad implemented in a fragment layout for a webview app. So, we have to implement it step by step.
First, we have to implement code under gradle.properties(Project Properties).
android.enableJetifier=true
android.defaults.buildfeatures.buildconfig=true
android.nonFinalResIds=false
Second, we must implement Facebook[Meta] dependency in the build.gradle(Module :app).
// Facebook[Meta] Ads Dependency
implementation 'com.facebook.android:audience-network-sdk:6.17.0'
Now, we have implemented a hardware accelerator in the Android.Manifest.xml file.
android:hardwareAccelerated="true"
Third, we must create a Java class that can help show interstitial ads when users press the back button.
::::: Java Code Implementation :::::
Now, we have to create a package named FacebookInterstitialAds then under this package, we have to create a Java file named InitializeAds. After that, we have to create an Ads Unit for banner ads.
First, we have to implement code InitializeAds file.
Now, we have to create an Interstitial Ads variable.
public static InterstitialAd interstitialAd;
We have to create two methods loadAds and showInterstitialAds.
First, we have to implement loadAds methods.
public static void loadAds(Activity activity) {
}
Under this method, we have to initialize the Audience Network.
AudienceNetworkAds.initialize(activity);
Now, we have to implement Ads Unit ID.
interstitialAd = new InterstitialAd(activity, "IMG_16_9_APP_INSTALL#YOUR_PLACEMENT_ID");
Now, we have to create an InterstitialAdListener method.
InterstitialAdListener interstitialAdListener = new InterstitialAdListener() {
@Override
public void onError(Ad ad, AdError adError) {
}
@Override
public void onAdLoaded(Ad ad) {
}
@Override
public void onAdClicked(Ad ad) {
}
@Override
public void onLoggingImpression(Ad ad) {
}
@Override
public void onInterstitialDisplayed(Ad ad) {
}
@Override
public void onInterstitialDismissed(Ad ad) {
InitializeAds.interstitialAd = null;
InitializeAds.loadAds(activity);
}
};
Now, we have to implement load the ad. Load Ads implemented out of the loadAds method.
// load the ad
interstitialAd.loadAd(
interstitialAd.buildLoadAdConfig()
.withAdListener(interstitialAdListener)
.build());
Second, we have to implement showInterstitialAds methods.
public static void showInterstitialAds(Context context) {
}
Now, we have implemented under showInterstitialAds method.
if (interstitialAd == null || !interstitialAd.isAdLoaded()) {
return;
}
if (interstitialAd.isAdInvalidated()) {
return;
}
// Show the ad
interstitialAd.show();
Now, we have to create a loadAds file.
public class LoadAds extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
InitializeAds.loadAds(LoadAds.this);
}
}
Finally, we have to show ads in Fragment Layout when webview back presses.
InitializeAds.showInterstitialAds(getActivity());
::::: Thank You :::::