Admob Rewarded Ads?

SLotman

Active member
3rd Party Module Dev
Tutorial Author
Joined
Jul 3, 2017
Messages
214
A small update - sorry I couldn't do more for now since I'm @ a hospital with my father who will do a complicated exam tomorrow.

The code below will attempt 'non stop' to load an ad if it fails to load. I plan to change this later if possible for a function to manually try again instead of this. It also has other functions to retrieve the type of reward (the default returns a string 'coins') and the amount (the default returns an int, 10) - those values will reset once you show a new ad.

It alsos pause and resume your game when an ad is shown :)

rewardedads.cxs:
Code:
#Rem
    Admob Rewarded ads module for Cerberus-X
    based on Interstial ads module on brl.admob  

    version 1.1 - 18 November 2022
        • Added suspend/resume support
        • If an ad fails to load, keep trying to load it again.
        • support for type and amount of rewards received       

    version 1.0 - 16 November 2022
        • First version      

----------------------------------------------------------------        
    Created by José Lucio "SLotman"
----------------------------------------------------------------        

    SETUP NEEDED: 

    (1) Open [project build]\android\gradletemplate\app\src\main\AndroidManifest.xml and add
    just before ${ANDROID_MANIFEST_APPLICATION}:  

    <meta-data
        android:name="com.google.android.gms.ads.APPLICATION_ID"
        android:value="real_app_id_generated_by_admob_here"/>

   (2) Open [project build]/android/gradletemplate/build.gradle

   replace every
       maven {
            url "https://maven.google.com"
      }

   with
       mavenCentral()
#End

Import mojo.app
Import mojo.graphics
Import mojo.input

#If TARGET="android"
  #If ANDROID_LIBGOOGLEPLAY_AVAILABLE
     Import brl.admob
  #End
  Import "native/rewardedads.java"
#End If

Extern

Class AdmobRewarded Extends Null = "BBAdmobRewarded"
    Function GetAdmobRewarded:AdmobRewarded(adUnitId:String)
    Method ShowAdViewRewarded:Void()
    Method isLoaded:Bool()            ' was the ad loaded?
    Method earnedReward:Bool()        ' did the user earned the reward?
    Method isClosed:Bool()            ' was the ad closed?
    Method failed:Bool()                ' failed to load the ad?
    Method rewardAmount:Int()        ' ammount of reward received
    Method rewardType:String()        ' type of reward received
End Class

Public

#If TARGET="android"
    #ANDROID_APP_LABEL="Rewarded ads"
    #ANDROID_APP_PACKAGE="com.icongames.rewardedAdsTest"
    #ANDROID_SCREEN_ORIENTATION="sensorPortrait"                    '"user", "portrait", "landscape"    
    #ANDROID_VERSION_CODE="001"
    #ANDROID_VERSION_NAME="0.01"

    ' test ads
    #ADMOB_PUBLISHER_ID = "ca-app-pub-3940256099942544/5224354917"
#End

Class Game Extends App
    Global IDLE:Int = 0
    Global AD_VISIBLE:Int = 1
    Global AD_CLOSED:Int = 2
    Global UPDATE_RATE:Int = 30     

    Field state:Int
    Field admobRewarded:AdmobRewarded

    Method OnCreate()
#If TARGET="android"    
                ' test ads
        admobRewarded = AdmobRewarded.GetAdmobRewarded("ca-app-pub-3940256099942544/5224354917")
#End
        SetUpdateRate UPDATE_RATE
        state = IDLE
    End Method

    Method OnUpdate()

        Select state
            Case IDLE
                If admobRewarded.isLoaded() Then
                    If TouchHit(0) Then
                        Print "Showing rewarded ad..."
                        admobRewarded.ShowAdViewRewarded()
                        state = AD_VISIBLE
                    End If
                Else
                    ' failed to load ad
                    If admobRewarded.failed() Then
                        Print "Failed to load ad!"
                        state = IDLE
                    End If
                End If     

            Case AD_VISIBLE
                If admobRewarded.isClosed() Then
                    state = AD_CLOSED
                End If 

            Case AD_CLOSED
                If admobRewarded.earnedReward() Then
                    Print "Yay! Reward earned"
                    Print "Reward amount:" + admobRewarded.rewardAmount()
                    Print "Reward type:" + admobRewarded.rewardType()
                Else
                    Print "Sorry, no reward."
                End If     
                state = IDLE
        End Select
    End Method

    Method OnRender()
        Cls(0,0,0)
        Select state
            Case IDLE
                If admobRewarded.isLoaded() Then
                    SetColor 255,255,255
                    DrawText "Touch the screen to open the ad!", 10,10
                End If
               
            Case AD_VISIBLE
            Case AD_CLOSED
        End Select
    End Method    

    Method OnSuspend()
        Print "App suspended!"
    End Method

    Method OnResume()
        Print "App resumed!"
    End Method
End Class

Function Main()
    New Game()
End Function

--- split to fit into messages ---
 

SLotman

Active member
3rd Party Module Dev
Tutorial Author
Joined
Jul 3, 2017
Messages
214
native/rewardedads.java:
Code:
/*
    Admob Rewarded ads module for Cerberus-X
    based on Interstial ads module on brl.admob
    
    version 1.1 - 18 November 2022
        • Added suspend/resume support
        • If an ad fails to load, keep trying to load it again.
        • support for type and amount of rewards received
        
    version 1.0 - 16 November 2022
        • First version
        
----------------------------------------------------------------        
    Created by José Lucio "SLotman"
----------------------------------------------------------------    
*/

import com.google.android.gms.ads.rewarded.RewardedAd;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.NonNull;             
import com.google.android.gms.ads.AdError;      
import com.google.android.gms.ads.MobileAds;      
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.initialization.InitializationStatus;    
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;    
import com.google.android.gms.ads.OnUserEarnedRewardListener;
import com.google.android.gms.ads.rewarded.RewardItem;
import com.google.android.gms.ads.rewarded.RewardedAd;
import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback;


class BBAdmobRewarded implements Runnable {
    static BBAdmobRewarded _admob;
    static Activity _activity;

    private RewardedAd _rewardedAd;
    boolean _loaded;
    boolean _earned;
    boolean _closed;
    boolean _failed;
    String adUnitId;
    
    int _rewardAmount;
    String _rewardType;
    
    private static final String TAG = "[Cerberus]";


    // creates an instance of the object and start the thread
    static public BBAdmobRewarded GetAdmobRewarded(String adUnitId){
        Log.d(TAG, "Google Mobile Ads SDK");

        if( _admob==null ) _admob=new BBAdmobRewarded();
        _activity = BBAndroidGame.AndroidGame().GetActivity();

        if( Variables.__bb__MobileAds_init == false ) {
            Log.d(TAG, "BBAdmobRewarded MobileAds.initialize");
            MobileAds.initialize(_activity, new OnInitializationCompleteListener() {
                @Override
                public void onInitializationComplete(InitializationStatus initializationStatus) { }
            });
            Variables.__bb__MobileAds_init = true ;
        }

        _admob.startAd(adUnitId);
        return _admob;
    }
    
    public boolean isLoaded() { return _loaded; }
    public boolean isClosed() { return _closed; }
    public boolean earnedReward() { return _earned;     }
    public boolean failed() { return _failed; }
    public int rewardAmount() { return _rewardAmount; }
    public String rewardType() { return _rewardType; }

    public void run(){
    
        if( _rewardedAd != null ){
            Log.d(TAG, "BBAdmobRewarded run() -> _rewardedAd.show");
            _failed = false;
            _rewardedAd.show(_activity,
            new OnUserEarnedRewardListener() {
                @Override
                public void onUserEarnedReward(@NonNull RewardItem rewardItem) {
                    // Handle the reward.
                    Log.d(TAG, "The user earned the reward.");
                    _rewardAmount = rewardItem.getAmount();
                    _rewardType = rewardItem.getType();
                    _earned = true;
                }
            });
            
            return;
        } else {    
            Log.e(TAG, "BBAdmobRewarded run() -> _rewardedAd = null");    
            _loaded = false;
            _earned = false;
            _closed = false;
            _rewardAmount = 0;
            _rewardType = "";
        }
        
        // load the first ad
        loadRewardedAd();
    }
    
    // start the thread 
    private void startAd(String adUnitId){
        Log.d(TAG, "BBAdmobRewarded startAd()");
        this.adUnitId = adUnitId;
        BBAndroidGame.AndroidGame().GetGameView().post(this);
    }

    private void loadRewardedAd() {
        if (_rewardedAd == null) {
          _loaded = false;
          Log.d(TAG, "BBAdmobRewarded adRequest");
          AdRequest adRequest = new AdRequest.Builder().build();
          
          RewardedAd.load(
              _activity,
              this.adUnitId,
              adRequest,
              new RewardedAdLoadCallback() {
                @Override
                public void onAdLoaded(@NonNull RewardedAd rewardedAd) {
                    Log.d(TAG, "BBAdmobRewarded onAdLoaded");
                    _loaded=true;
                    _failed = false;
                    _rewardedAd = rewardedAd;
                    
                    _rewardedAd.setFullScreenContentCallback(new FullScreenContentCallback()
                    {
                        @Override
                        public void onAdDismissedFullScreenContent() {
                            // Called when fullscreen content is dismissed.
                            Log.d(TAG, "BBAdmobRewarded FullScreenContentCallback -> The ad was dismissed.");
                            _closed = true;
                            Log.d(TAG, "onAdDismissedFullScreenContent - Trying to resume game...");
                            BBAndroidGame.AndroidGame().ResumeGame();
                            _rewardedAd = null;
                            _admob.loadRewardedAd();
                        }
                                
                        @Override
                        public void onAdFailedToShowFullScreenContent(AdError adError) {
                            // Called when fullscreen content failed to show.
                            Log.d(TAG, "BBAdmobRewarded FullScreenContentCallback -> The ad failed to show.");
                            Log.d(TAG, "OnAdFailedToShowFullScreenContent - Trying to resume game...");
                            BBAndroidGame.AndroidGame().ResumeGame();
                            _rewardedAd = null;
                            _closed = true;
                            _earned = false;
                            _loaded = false;
                        }
                                
                        @Override
                        public void onAdShowedFullScreenContent() {
                            // Called when fullscreen content is shown.
                            Log.d(TAG, "onAdShowedFullScreenContent - Trying to suspend game...");
                            BBAndroidGame.AndroidGame().SuspendGame();

                            _rewardedAd = null;
                            _earned = false;
                            _rewardAmount = 0;
                            _rewardType = "";                            
                            _closed=false;
                            Log.d(TAG, "BBAdmobRewarded FullScreenContentCallback -> The ad was shown.");
                            //loadRewardedAd();
                        }
                    });                  
                }

                @Override
                public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                  // Handle the error.
                  Log.d(TAG, loadAdError.getMessage());
                  Log.d(TAG, "onAdFailedToLoad - Trying to resume game...");
                  BBAndroidGame.AndroidGame().ResumeGame();
                  _admob._failed = true;
                  _rewardedAd = null;
                  
                  // try to load an ad again...
                  _admob.loadRewardedAd();
                }

              });
              
        }
    }

    // displays the ad to the user if it is ready
    public void ShowAdViewRewarded( ){
        if (_rewardedAd != null ) {
            if( _loaded ){
                Log.d(TAG, "BBAdmobRewarded ShowAdViewRewarded() -> _loaded = true");
                BBAndroidGame.AndroidGame().GetGameView().post(this);
            } else {    
                Log.e(TAG, "BBAdmobRewarded ShowAdViewRewarded() -> _loaded = false");
            }
        } else {    
            Log.e(TAG, "BBAdmobRewarded ShowAdViewRewarded() -> _rewardedAd = null");    
            _loaded = false;
            _earned = false;
            _closed = false;
        }
    }

}

Once things settle down, I may post this over to github, it could help someone out there :)
 

Wingnut

Well-known member
3rd Party Module Dev
Tutorial Author
Joined
Jan 2, 2020
Messages
1,196
Thanks, and good luck!
 
Top Bottom