How to use ads in android studio ?? ( Ads )

Add in build.gradle  

implementation 'com.google.android.gms:play-services-ads:22.6.0'


Add this to manifest file
<manifest>
 
<application>
   
<!-- Sample AdMob app ID: ca-app-pub-3940256099942544~3347511713 -->
   
<meta-data
       
android:name="com.google.android.gms.ads.APPLICATION_ID"
       
android:value="ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy"/>

 
</application>
</manifest>
the android:value will be your "appkey"

Add the following code to your MainActivity is can only we add once

import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;

public class MainActivity extends AppCompatActivity {
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView
(R.layout.activity_main);

       
MobileAds.initialize(this, new OnInitializationCompleteListener() {
           
@Override
           
public void onInitializationComplete(InitializationStatus initializationStatus) {
           
}
       
});
   
}
}



Implementing banner ads

Create it in xml 
# main_activity.xml
<com.google.android.gms.ads.AdView
   
xmlns:ads="http://schemas.android.com/apk/res-auto"
   
android:id="@+id/adView"
   
android:layout_width="wrap_content"
   
android:layout_height="wrap_content"
   
android:layout_centerHorizontal="true"
   
android:layout_alignParentBottom="true"
   
ads:adSize="BANNER"
   
ads:adUnitId="ca-app-pub-3940256099942544/6300978111">
</com.google.android.gms.ads.AdView>

or you can create programmatically

AdView adView = new AdView(this);

adView
.setAdSize(AdSize.BANNER);

adView
.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
// TODO: Add adView to your view hierarchy.

Implementing Interstitial ads



Simply add this below code in your activity in which you want to show add
Don't Forget To Chanr your ads key

InterstitialAd.load(this,"your ads key", adRequest,
        new InterstitialAdLoadCallback() {
            @Override
            public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
                // The mInterstitialAd reference will be null until
                // an ad is loaded.
                mInterstitialAd = interstitialAd;
                Log.i(TAG, "onAdLoaded");
                mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback(){
                    @Override
                    public void onAdClicked() {
                        // Called when a click is recorded for an ad.
                        Log.d(TAG, "Ad was clicked.");
                    }
                    @Override
                    public void onAdDismissedFullScreenContent() {
                        // Called when ad is dismissed.
                        // Set the ad reference to null so you don't show the ad a second time.
                        Log.d(TAG, "Ad dismissed fullscreen content.");
                        mInterstitialAd = null;
                    }
                    @Override
                    public void onAdFailedToShowFullScreenContent(AdError adError) {
                        // Called when ad fails to show.
                        Log.e(TAG, "Ad failed to show fullscreen content.");
                        mInterstitialAd = null;
                    }
                    @Override
                    public void onAdImpression() {
                        // Called when an impression is recorded for an ad.
                        Log.d(TAG, "Ad recorded an impression.");
                    }
                    @Override
                    public void onAdShowedFullScreenContent() {
                        // Called when ad is shown.
                        Log.d(TAG, "Ad showed fullscreen content.");
                    }
                });
                if (mInterstitialAd != null) {
                    mInterstitialAd.show(MainActivity.this);
                } else {
                    Log.d("TAG", "The interstitial ad wasn't ready yet.");
                }
            }
            @Override
            public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                // Handle the error
                Log.d(TAG, loadAdError.toString());
                mInterstitialAd = null;
                super.onAdFailedToLoad(loadAdError);
            }
        });


App Open Ads

Just simply create new java file call OpenAppAdd and copy below code

Don't Forget To Chanr your ads key
package com.devduos.encryptedpassword;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;
import androidx.lifecycle.ProcessLifecycleOwner;

import com.google.android.gms.ads.AdError;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.FullScreenContentCallback;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.appopen.AppOpenAd;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;

import java.util.Date;

public class OpenAppAdd extends Application implements Application.ActivityLifecycleCallbacks, LifecycleObserver {

private AppOpenAdManager appOpenAdManager;
private Activity currentActivity;
public long loadTime = 0;

@Override
public void onCreate() {
super.onCreate();
MobileAds.initialize(
this,
new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(InitializationStatus initializationStatus) {}
});
ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
appOpenAdManager = new AppOpenAdManager(this);
}

/** LifecycleObserver method that shows the app open ad when the app moves to foreground. */
@OnLifecycleEvent(Lifecycle.Event.ON_START)
protected void onMoveToForeground() {
// Show the ad (if available) when the app moves to foreground.
appOpenAdManager.showAdIfAvailable(currentActivity);
}



/** Show the ad if one isn't already showing. */



/** Inner class that loads and shows app open ads. */

/** Interface definition for a callback to be invoked when an app open ad is complete. */
public interface OnShowAdCompleteListener {
void onShowAdComplete();
}


private class AppOpenAdManager {

private static final String LOG_TAG = "AppOpenAdManager";
private static final String AD_UNIT_ID = "your ads key";

private AppOpenAd appOpenAd = null;
private boolean isLoadingAd = false;
private boolean isShowingAd = false;

/** Constructor. */
public AppOpenAdManager(OpenAppAdd myApplication) {}

/** Request an ad. */
private void loadAd(Context context) {
// We will implement this below.
// Do not load ad if there is an unused ad or one is already loading.
if (isLoadingAd || isAdAvailable()) {
return;
}

isLoadingAd = true;
AdRequest request = new AdRequest.Builder().build();
AppOpenAd.load(
context, AD_UNIT_ID, request,
AppOpenAd.APP_OPEN_AD_ORIENTATION_PORTRAIT,
new AppOpenAd.AppOpenAdLoadCallback() {
@Override
public void onAdLoaded(AppOpenAd ad) {
// Called when an app open ad has loaded.
Log.d(LOG_TAG, "Ad was loaded.");
appOpenAd = ad;
isLoadingAd = false;
loadTime = (new Date()).getTime();
}

@Override
public void onAdFailedToLoad(LoadAdError loadAdError) {
// Called when an app open ad has failed to load.
Log.d(LOG_TAG, loadAdError.getMessage());
isLoadingAd = false;
}
});
}
/** Shows the ad if one isn't already showing. */
public void showAdIfAvailable(
@NonNull final Activity activity
/*@NonNull OnShowAdCompleteListener onShowAdCompleteListener */){
// If the app open ad is already showing, do not show the ad again.
if (isShowingAd) {
Log.d(LOG_TAG, "The app open ad is already showing.");
return;
}

// If the app open ad is not available yet, invoke the callback then load the ad.
if (!isAdAvailable()) {
Log.d(LOG_TAG, "The app open ad is not ready yet.");
//** onShowAdCompleteListener.onShowAdComplete();
loadAd(OpenAppAdd.this);
return;
}

appOpenAd.setFullScreenContentCallback(
new FullScreenContentCallback() {

@Override
public void onAdDismissedFullScreenContent() {
// Called when fullscreen content is dismissed.
// Set the reference to null so isAdAvailable() returns false.
Log.d(LOG_TAG, "Ad dismissed fullscreen content.");
appOpenAd = null;
isShowingAd = false;

//** onShowAdCompleteListener.onShowAdComplete();
loadAd(activity);
}

@Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when fullscreen content failed to show.
// Set the reference to null so isAdAvailable() returns false.
Log.d(LOG_TAG, adError.getMessage());
appOpenAd = null;
isShowingAd = false;

//** onShowAdCompleteListener.onShowAdComplete();
loadAd(activity);
}

@Override
public void onAdShowedFullScreenContent() {
// Called when fullscreen content is shown.
Log.d(LOG_TAG, "Ad showed fullscreen content.");
}
});
isShowingAd = true;
appOpenAd.show(activity);
}


/** Check if ad exists and can be shown. */
private boolean isAdAvailable() {
return appOpenAd != null && wasLoadTimeLessThanNHoursAgo(4);
}
}

private boolean wasLoadTimeLessThanNHoursAgo(long numHours) {
long dateDifference = (new Date()).getTime() - this.loadTime;
long numMilliSecondsPerHour = 3600000;
return (dateDifference < (numMilliSecondsPerHour * numHours));
}


/** ActivityLifecycleCallback methods. */
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {}

@Override
public void onActivityStarted(Activity activity) {
// Updating the currentActivity only when an ad is not showing.
if (!appOpenAdManager.isShowingAd) {
currentActivity = activity;
}
}

@Override
public void onActivityResumed(Activity activity) {}

@Override
public void onActivityStopped(Activity activity) {}

@Override
public void onActivityPaused(Activity activity) {}

@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {}

@Override
public void onActivityDestroyed(Activity activity) {}

}

Change Application name in manifest file to java file name like :

<application
android:name=".OpenAppAdd"
android:allowBackup="true"

Comments

Popular posts from this blog

How to add layout inflator (Layout Inflators)