Signup/Sign In
APRIL 9, 2021

How to add Admob Rewarded Ads in Android App

    In this article we will learn to integrate Google Admob Rewarded Ad in you android app. Before going to coding part we will first learn some basics and features of Rewarded Ads. You can also learn about adding Banner ads and Interstitial Ads in android app from our previous tutorial

    Rewarded Ads:

    Rewarded ads is a full screen video ad of 10 second to 60 second which cover the entire screen of the user ,it is used in many apps and games for different purposes such as

    • unlocking the level or new skin in the game

    • skipping the level of the game

    • get premium content for free in apps or games

    • getting some extra coins or lifes in games

    Feature of Rewarded Ad

    • Support frequency cap means wecan decide how many ads are show to the user daily or hourly

    • User can interact with the ad as it also contains playable ads

    • The eCPM is hight as compare to Banner Ads and Interstitial Ads, so it leads to more revenue

    • support both Mobile phones and Tablets

    • fill rate is maximum

    • We can change the value of reward in the realtime using the google admob dashboard

    • If the user skiped the rewarded ad then also we will earn some revenue and if user watches the rewarded ad completely then the revenue earned is more than the skipped ad

    • Even work with low internet connection speed as the ads which are shown to the users will take less data

    So let's implement a simple Admob Rewarded Ad in our android app.

    Step 1: Create a new Project

    1. Open Your Android Studio Click on "Start a new Android Studio project"(Learn how to setup Android Studio and create your first Android project)

    2. Choose "Empty Activity" from the project template window and click Next

    3. Enter the App Name,Package name, save location, language(Java/Kotlin ,we use Java for this tutorial ) and minimum SDK(we are using API 19: Android 4.4 (KitKat) )

    4. Next click on Finish button after filling the above details

    5. Now wait for the project to finish building.

    Step 2: Adding the Mobile Ads SDK

    To show the ads in our app we have to first implement the Admob sdk in our app, to do so.

    Go to Gradle Scripts->build.gradle (Module: app) section and import below dependencies and click the "sync Now" show at the top:

    dependencies {
         // adding Admob SDK
         implementation 'com.google.android.gms:play-services-ads:19.4.0'
    }

    Now our build.gradle file look like:

    apply plugin: 'com.android.application'
    
    android {
        compileSdkVersion 29
        buildToolsVersion "29.0.3"
    
        defaultConfig {
            applicationId "com.studytonight.project"
            minSdkVersion 19
            targetSdkVersion 29
            versionCode 1
            versionName "1.0"
    
            testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        }
    
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
            }
        }
    }
    
    dependencies {
        implementation fileTree(dir: "libs", include: ["*.jar"])
        implementation 'androidx.appcompat:appcompat:1.2.0'
        implementation 'androidx.constraintlayout:constraintlayout:2.0.2'
        testImplementation 'junit:junit:4.12'
        androidTestImplementation 'androidx.test.ext:junit:1.1.2'
        androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
    
        // adding Admob SDK
        implementation 'com.google.android.gms:play-services-ads:19.4.0'
    
    }

    Step 3: Modify AndroidManifest.xml

    Go to app->manifests->AndroidManifest.xml file and add the internet permission to the Android Manifest file

    <manifest>
    <uses-permission android:name= "android.permission.INTERNET"/> 
    </manifest>

    Now we add add our AdMob AppId to your in the AndroidManifest file by adding the <meta-data> tag inside the <application> tag

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

    To show video ads smoothly in the Rewarded ad views, hardware acceleration must be turned on. In Android the hardware acceleration is enabled by default, we can also enable and disable it for the entire or for each activity separately in our android manifest file as show below:

    <!-- for the entire app --> 
    <application
        android:hardwareAccelerated="true"></application>
    <!-- for the each activity -->
    <application>
            <activity
               android:hardwareAccelerated="true"> </activity>
    </application>

    The complete code of AndroidManifest.xml file is shown below:

    <?xml version= "1.0" encoding= "utf-8"?>
    <manifest xmlns:android= "http://schemas.android.com/apk/res/android"
        package= "com.studytonight.project">
    
        <!-- adding internet permission to show allow app to use internet to load and show ads -->
        <uses-permission android:name= "android.permission.INTERNET"/>
    
        <!-- hardware Acceleration is turned on for the entire app -->
        <application
            android:hardwareAccelerated= "true"
            android:allowBackup= "true"
            android:icon= "@mipmap/ic_launcher"
            android:label= "@string/app_name"
            android:roundIcon= "@mipmap/ic_launcher_round"
            android:supportsRtl= "true"
            android:theme= "@style/AppTheme">
            <activity
                android:screenOrientation="portrait"
                android:name= ".MainActivity">
                <intent-filter>
                    <action android:name= "android.intent.action.MAIN" />
    
                    <category android:name= "android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    
            <!-- Adding AdMob App Id -->
            <meta-data
                android:name= "com.google.android.gms.ads.APPLICATION_ID"
                android:value= "ca-app-pub-3940256099942544~3347511713"/>
    
        </application>
    
    </manifest>

    Step 4: Modify activity_main.xml

    We will now create 2 Buttons to load and show Rewarded ad insde a vertical linearLayout:

    <!-- vertical linear layout with 2  button -->
    <LinearLayout
        android:layout_centerInParent= "true"
        android:layout_margin= "16dp"
        android:orientation= "vertical"
        android:layout_width= "match_parent"
        android:layout_height= "wrap_content">
    
        <!-- Simple Buttons to Load Rewarded Ad when clicked -->
        <Button
            android:textSize= "24dp"
            android:layout_margin= "16dp"
            android:id= "@+id/loadRewardedBtn"
            android:text= "Load Rewarded  Ad"
            android:fontFamily= "serif"
            android:textStyle= "bold"
            android:textColor= "#ffffff"
            android:background= "@color/colorPrimary"
            android:layout_width= "match_parent"
            android:layout_height= "60dp"/>
    
        <!-- Simple Buttons to Show  Rewarded Ad if is is loaded when clicked -->
        <Button
            android:textSize= "24dp"
            android:layout_margin= "16dp"
            android:id= "@+id/showRewardedBtn"
            android:text= "Show Rewarded  Ad"
            android:fontFamily= "serif"
            android:textStyle= "bold"
            android:textColor= "#ffffff"
            android:background= "@color/colorPrimary"
            android:layout_width= "match_parent"
            android:layout_height= "60dp"/>
    
    </LinearLayout>

    The complete code of activity_main.xml is show below:

    <?xml version=  "1.0" encoding=  "utf-8"?>
    <RelativeLayout xmlns:android=  "http://schemas.android.com/apk/res/android"
        xmlns:app=  "http://schemas.android.com/apk/res-auto"
        xmlns:tools=  "http://schemas.android.com/tools"
        android:layout_width=  "match_parent"
        android:layout_height=  "match_parent"
        tools:context=  ".MainActivity">
    
        <!-- vertical linear layout with 2  button -->
        <LinearLayout
            android:layout_centerInParent= "true"
            android:layout_margin= "16dp"
            android:orientation= "vertical"
            android:layout_width= "match_parent"
            android:layout_height= "wrap_content">
    
            <!-- Simple Buttons to Load Rewarded Ad when clicked -->
            <Button
                android:textSize= "24dp"
                android:layout_margin= "16dp"
                android:id= "@+id/loadRewardedBtn"
                android:text= "Load Rewarded  Ad"
                android:fontFamily= "serif"
                android:textStyle= "bold"
                android:textColor= "#ffffff"
                android:background= "@color/colorPrimary"
                android:layout_width= "match_parent"
                android:layout_height= "60dp"/>
    
            <!-- Simple Buttons to Show  Rewarded Ad if is is loaded when clicked -->
            <Button
                android:textSize= "24dp"
                android:layout_margin= "16dp"
                android:id= "@+id/showRewardedBtn"
                android:text= "Show Rewarded  Ad"
                android:fontFamily= "serif"
                android:textStyle= "bold"
                android:textColor= "#ffffff"
                android:background= "@color/colorPrimary"
                android:layout_width= "match_parent"
                android:layout_height= "60dp"/>
    
        </LinearLayout>
    
    </RelativeLayout>

    Step 5: MainActivity.java file

    First we have to import the library inside the ActivityMain.java,

    //library for Button, View and Toast
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;
    
    // important library for Google adMob
    import com.google.android.gms.ads.AdError;
    import com.google.android.gms.ads.AdRequest;
    import com.google.android.gms.ads.LoadAdError;
    import com.google.android.gms.ads.MobileAds;
    import com.google.android.gms.ads.initialization.InitializationStatus;
    import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
    import com.google.android.gms.ads.rewarded.RewardItem;
    import com.google.android.gms.ads.rewarded.RewardedAd;
    import com.google.android.gms.ads.rewarded.RewardedAdCallback;
    import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback;

    Now inside the MainActivity class we create object of RewardedAd, Button (loadAdBtn, showAdBtn)

    //creating Object of RewardedAd
    private RewardedAd rewardedAd ;
    
    //creating Object of Buttons
    private Button loadAdBtn;
    private Button showAdBtn;

    Next, we will create Rewarded Ad callback object(RewardedAdLoadCallback) to know whether or not the ad is loaded and other callback(RewardedAdCallback) to know the status of Rewarded ad after it is loaded, the code is shown below:

    //creating Object of Rewarded Ad Load Callback
    RewardedAdLoadCallback rewardedAdLoadCallback;
    
    //creating Object of Rewarded Ad Callback
    RewardedAdCallback rewardedAdCallback;

    Now inside the onCreate we initialize the MobileAds and will show a simple toast message when initialization is completed using the below code:

    //initializing the Google Admob SDK
    MobileAds.initialize (this, new OnInitializationCompleteListener() {
        @Override
        public void onInitializationComplete( InitializationStatus initializationStatus ) {
    
            //Showing a simple Toast Message to the user when The Google AdMob Sdk Initialization is Completed
            Toast.makeText (MainActivity.this, "AdMob Sdk Initialize "+ initializationStatus.toString(), Toast.LENGTH_LONG).show();
    
        }
    });

    Next, we will initilize the Button and RewardedAd inside the onCreate method after initializing the SDK. RewardedAd constructor has 2 parameter:

    • 1st Parameter : Context

    • 2nd Paramnter: AdId (we are using test id provided by admob for this tutorial ,you can change it with your own app rewarded ad id)

    //Initializing the RewardedAd  objects
    rewardedAd = new RewardedAd( this, "ca-app-pub-3940256099942544/5224354917" ) ;
    
    
    // Initializing the Button  objects to their respective views from activity_main.xml file
    loadAdBtn = (Button) findViewById(R.id.loadRewardedBtn);
    showAdBtn = (Button) findViewById(R.id.showRewardedBtn);

    Now we will create a simple method loadRewardedAd() to load the Rewarded Ad inside MainActivity class as show below:

    private void loadRewardedAd()
    {
        // Creating  an Ad Request
        AdRequest adRequest = new AdRequest.Builder().build();
    
        // load Rewarded Ad with the Request
        rewardedAd.loadAd(adRequest, rewardedAdLoadCallback);
    
        // Showing a simple Toast message to user when Rewarded an ad is Loading
        Toast.makeText (MainActivity.this, "Rewarded Ad is loading ", Toast.LENGTH_LONG).show();
    }

    Next, we create one more method showRewardedAd() to show the Rewarded Ad to the user if it is loaded and if it is not loaded we will load the Rewarded ad using the above method loadRewardedAd() and if the ad is loaded we initialize the RewardedAdCallback object and show the appropriate toast message to the user about the status of the rewarded video ad, as shown below:

    private void showRewardedAd() {
    	if (rewardedAd.isLoaded()) {
    
    		//creating the Rewarded Ad Callback and showing the user appropriate message
    		rewardedAdCallback = new RewardedAdCallback() {@Override
    			public void onRewardedAdOpened() {
    				// Showing a simple Toast message to user when Rewarded Ad is opened
    				Toast.makeText(MainActivity.this, "Rewarded Ad is Opened", Toast.LENGTH_LONG).show();
    			}
    
    			@Override
    			public void onRewardedAdClosed() {
    				// Showing a simple Toast message to user when Rewarded Ad is closed
    				Toast.makeText(MainActivity.this, "Rewarded Ad Closed", Toast.LENGTH_LONG).show();
    
    			}
    
    			@Override
    			public void onUserEarnedReward(RewardItem reward) {
    				// Showing a simple Toast message to user when user earned the reward by completely watching the Rewarded Ad
    				Toast.makeText(MainActivity.this, "You won the reward :" + reward.getAmount(), Toast.LENGTH_LONG).show();
    
    			}
    
    			@Override
    			public void onRewardedAdFailedToShow(AdError adError) {
    				// Showing a simple Toast message to user when Rewarded Ad Failed to Show
    				Toast.makeText(MainActivity.this, "Rewarded Ad failed to show due to error:" + adError.toString(), Toast.LENGTH_LONG).show();
    
    			}
    		};
    
    		//showing the ad Rewarded Ad if it is loaded
    		rewardedAd.show(MainActivity.this, rewardedAdCallback);
    
    		// Showing a simple Toast message to user when an Rewarded ad is shown to the user
    		Toast.makeText(MainActivity.this, "Rewarded Ad  is loaded and Now showing ad  ", Toast.LENGTH_LONG).show();
    
    	}
    	else {
    		//Load the Rewarded ad if it is not loaded
    		loadRewardedAd();
    
    		// Showing a simple Toast message to user when Rewarded ad is not loaded
    		Toast.makeText(MainActivity.this, "Rewarded Ad is not Loaded ", Toast.LENGTH_LONG).show();
    
    	}
    
    }

    Now we will create a click listener inside the onCreate method so that the above function are executed when the buttons are clicked, which we have created in our activity_main.xml file:

    //OnClickListener listeners for loadAdBtn and showAdBtn buttons
    loadAdBtn.setOnClickListener( new View.OnClickListener() {
        @Override
        public void onClick( View view) {
            //calling the loadRewardedAd method to load  the Rewarded Ad
            loadRewardedAd();
        }
    });
    
    showAdBtn.setOnClickListener( new View.OnClickListener() {
        @Override
        public void onClick( View view) {
            //calling the showRewardedAd method to show the Rewarded Ad
            showRewardedAd();
        }
    });

    To know the status of the Rewarded ad if it is loaded or not we intilaize the RewardedAdLoadCallback object inside the onCreate() method as shown below in the code:

    // creating  RewardedAdLoadCallback for Rewarded Ad with some 2 Override methods
    rewardedAdLoadCallback =new RewardedAdLoadCallback(){
        @Override
        public void onRewardedAdLoaded() {
            // Showing a simple Toast message to user when Rewarded Ad Failed to Load
            Toast.makeText (MainActivity.this, "Rewarded Ad is Loaded", Toast.LENGTH_LONG).show() ;
        }
    
        @Override
        public void onRewardedAdFailedToLoad( LoadAdError adError) {
            // Showing a simple Toast message to user when Rewarded Ad Failed to Load
            Toast.makeText (MainActivity.this, "Rewarded Ad is Loaded", Toast.LENGTH_LONG).show() ;
        }
    };

    Overridable methods of RewardedAdLoadCallback

    Here is a list of overridable methods of RewardedAdLoadCallback:

    public void onRewardedAdLoaded()

    The onRewardedAdLoaded method is executed when an Rewarded ad is loaded. We can update the UI or do other stuff if the ad is loaded such as give user more lives or coins in case of game or providing premium content to user for watching the rewarded video ad.
    public void onRewardedAdFailedToLoad(LoadAdError adError)

    The onRewardedAdFailedToLoad method is the only one which includes a parameter. The adError parameter is of type LoadAdError describes which type of error is occurred

    Overridable methods of RewardedAdCallback

    Here is a list of overridable methods of RewardedAdCallback:

    public void onRewardedAdOpened() 

    The onRewardedAdOpened() method is executed when the ad is shown to the user and coverted the device full screen.
    public void  onRewardedAdClosed()

    The onRewardedAdClosed() method is executed when the user clicks close ad button or press the back button and closes the Rewarded ad
    public void onUserEarnedReward( RewardItem reward )

    This method is executed after onRewardedAdOpened(), when a user had completed watching the full rewarded ad and it takes only one parameter RewardItem (we can get the value of reward by using reward.getAmount() and we can change the value of reward iteam from the admob dashboard in the real time)

    public void onRewardedAdFailedToShow( AdError adError ) 

    The onRewardedAdFailedToShow() method is executed when the Rewarded ad fails to show and it contains one parameter of type AdError which show the error. We can get the error code using adError.getCode().

    The complete code of MainActivity.java is shown below:

    package com.studytonight.project;
    
    import androidx.appcompat.app.AppCompatActivity;
    import android.os.Bundle;
    
    //library for Button, View and Toast
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;
    
    // important library for Google adMob
    import com.google.android.gms.ads.AdError;
    import com.google.android.gms.ads.AdRequest;
    import com.google.android.gms.ads.LoadAdError;
    import com.google.android.gms.ads.MobileAds;
    import com.google.android.gms.ads.initialization.InitializationStatus;
    import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
    import com.google.android.gms.ads.rewarded.RewardItem;
    import com.google.android.gms.ads.rewarded.RewardedAd;
    import com.google.android.gms.ads.rewarded.RewardedAdCallback;
    import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback;
    
    public class MainActivity extends AppCompatActivity {
    
    	//creating Object of RewardedAd
    	private RewardedAd rewardedAd;
    
    	//creating Object of Buttons
    	private Button loadAdBtn;
    	private Button showAdBtn;
    
    	//creating Object of RewardedAdLoadCallback
    	RewardedAdLoadCallback rewardedAdLoadCallback;
    
    	//creating Object of RewardedAdCallback
    	RewardedAdCallback rewardedAdCallback;
    
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    
    		//initializing the Google Admob SDK
    		MobileAds.initialize(this, new OnInitializationCompleteListener() {@Override
    			public void onInitializationComplete(InitializationStatus initializationStatus) {
    
    				//Showing a simple Toast Message to the user when The Google AdMob Sdk Initialization is Completed
    				Toast.makeText(MainActivity.this, "AdMob Sdk Initialize " + initializationStatus.toString(), Toast.LENGTH_LONG).show();
    
    			}
    		});
    
    		//Initializing the RewardedAd  objects
    		rewardedAd = new RewardedAd(this, "ca-app-pub-3940256099942544/5224354917");
    
    		// Initializing the Button  objects to their respective views from activity_main.xml file
    		loadAdBtn = (Button) findViewById(R.id.loadRewardedBtn);
    		showAdBtn = (Button) findViewById(R.id.showRewardedBtn);
    
    		//OnClickListener listeners for loadAdBtn and showAdBtn buttons
    		loadAdBtn.setOnClickListener(new View.OnClickListener() {@Override
    			public void onClick(View view) {
    				//calling the loadRewardedAd method to load  the Rewarded Ad
    				loadRewardedAd();
    			}
    		});
    
    		showAdBtn.setOnClickListener(new View.OnClickListener() {@Override
    			public void onClick(View view) {
    				//calling the showRewardedAd method to show the Rewarded Ad
    				showRewardedAd();
    			}
    		});
    
    		// creating  RewardedAdLoadCallback for Rewarded Ad with some 2 Override methods
    		rewardedAdLoadCallback = new RewardedAdLoadCallback() {@Override
    			public void onRewardedAdLoaded() {
    				// Showing a simple Toast message to user when Rewarded Ad Failed to Load
    				Toast.makeText(MainActivity.this, "Rewarded Ad is Loaded", Toast.LENGTH_LONG).show();
    			}
    
    			@Override
    			public void onRewardedAdFailedToLoad(LoadAdError adError) {
    				// Showing a simple Toast message to user when Rewarded Ad Failed to Load
    				Toast.makeText(MainActivity.this, "Rewarded Ad is Loaded", Toast.LENGTH_LONG).show();
    			}
    		};
    	}
    
    	private void loadRewardedAd() {
    		// Creating  an Ad Request
    		AdRequest adRequest = new AdRequest.Builder().build();
    
    		// load Rewarded Ad with the Request
    		rewardedAd.loadAd(adRequest, rewardedAdLoadCallback);
    
    		// Showing a simple Toast message to user when Rewarded an ad is Loading
    		Toast.makeText(MainActivity.this, "Rewarded Ad is loading ", Toast.LENGTH_LONG).show();
    	}
    
    	private void showRewardedAd() {
    		if (rewardedAd.isLoaded()) {
    
    			//creating the Rewarded Ad Callback and showing the user appropriate message
    			rewardedAdCallback = new RewardedAdCallback() {@Override
    				public void onRewardedAdOpened() {
    					// Showing a simple Toast message to user when Rewarded Ad is opened
    					Toast.makeText(MainActivity.this, "Rewarded Ad is Opened", Toast.LENGTH_LONG).show();
    				}
    
    				@Override
    				public void onRewardedAdClosed() {
    					// Showing a simple Toast message to user when Rewarded Ad is closed
    					Toast.makeText(MainActivity.this, "Rewarded Ad Closed", Toast.LENGTH_LONG).show();
    				}
    
    				@Override
    				public void onUserEarnedReward(RewardItem reward) {
    					// Showing a simple Toast message to user when user earned the reward by completely watching the Rewarded Ad
    					Toast.makeText(MainActivity.this, "You won the reward :" + reward.getAmount(), Toast.LENGTH_LONG).show();
    				}
    
    				@Override
    				public void onRewardedAdFailedToShow(AdError adError) {
    					// Showing a simple Toast message to user when Rewarded Ad Failed to Show
    					Toast.makeText(MainActivity.this, "Rewarded Ad failed to show due to error:" + adError.toString(), Toast.LENGTH_LONG).show();
    				}
    			};
    
    			//showing the ad Rewarded Ad if it is loaded
    			rewardedAd.show(MainActivity.this, rewardedAdCallback);
    
    			// Showing a simple Toast message to user when an Rewarded ad is shown to the user
    			Toast.makeText(MainActivity.this, "Rewarded Ad  is loaded and Now showing ad  ", Toast.LENGTH_LONG).show();
    		}
    		else {
    			//Load the Rewarded ad if it is not loaded
    			loadRewardedAd();
    
    			// Showing a simple Toast message to user when Rewarded ad is not loaded
    			Toast.makeText(MainActivity.this, "Rewarded Ad is not Loaded ", Toast.LENGTH_LONG).show();
    
    		}
    	}
    }

    Output:

    In the below snapshots, you can see how the Rewarded Ad will look in the android application.

    Admob Rewarded Video Ad Example

    When Rewarded Ad is shown to the user:

    Admob Rewarded Video Ad Example

    Conclusion:

    In just 5 simple steps we have integrated and shown you the basic example for creating a Google Admob Rewarded Video Ad. If you face any issue while doing this, please share it in the comment section below and we will be happy to help.

    Also Read: Add Admob Native Ad in Android App

    K S Lohan is an accomplished author and expert in technical writing on Android language and develop android App. He is highly skilled at communicating complex programming concepts in a clear and concise manner.
    IF YOU LIKE IT, THEN SHARE IT
    Advertisement

    RELATED POSTS