Unity3d AdMob rewarded ad not showing - android

I am doing some simple app with two buttons... first button is sending request for Awarded (test) ad and then second shows the ad.
Here is my code:
using GoogleMobileAds.Api;
using UnityEngine;
using System;
public class adManager : MonoBehaviour
{
RewardBasedVideoAd rewardedAd;
public void Start()
{
rewardedAd = RewardBasedVideoAd.Instance;
requestVideo();
}
public void requestVideo()
{
Debug.Log("Video Requested!");
string adID = "My ad ID";
AdRequest request = new AdRequest.Builder()
.AddTestDevice(AdRequest.TestDeviceSimulator) // Simulator.
.AddTestDevice("BD6E7C35B6F8FA70") // My test device.
.Build();
rewardedAd.LoadAd(request, adID);
}
public void showBannerAd()
{
if (rewardedAd.IsLoaded())
{
Debug.Log("AdAvailible!");
rewardedAd.OnAdRewarded += HandleOnAdRewarded;
rewardedAd.Show();
}
else
{
Debug.Log("AdNotAvailible!");
}
}
public void HandleOnAdRewarded(object sender, EventArgs args)
{
Debug.Log("You are rewarded!");
}
public event EventHandler<Reward> OnAdRewarded;
}
Is something wrong with my code or something else?
I tried interstitial and banner ad and they WORKED.
Thanks for help.

Related

After updating Google Ads SDK InterstitialAd is deprecated, How to resolve?

After updating Google Ads SDK to 19.7.0 gives a deprecated warning message for InterstitialAd, while I searched this link for resolving the issue but not succeed.
how can I resolve it?
Here my code
public void InterstitialAdmob() {
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(Util.ADMOBINTER);
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
requestNewInterstitial();
}
});
requestNewInterstitial();
}
protected void requestNewInterstitial() {
AdRequest adRequest = new AdRequest.Builder().addTestDevice(ADMOBDEV).build();
mInterstitialAd.loadAd(adRequest);
}
// for showing ads
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
and developer site or suggestion
Check the new API examples here:
https://developers.google.com/admob/android/interstitial-fullscreen
Warning: There are many breaking changes coming in version 20.0.0. Version 19.7.0 introduces many new APIs, and deprecates or renames many classes in preparation for version 20.0.0. Please read the migration guide for more details on the changes.
https://developers.google.com/admob/android/migration
This is what I did on my fragment, with just 4 steps.
1.Replace the deprecated import:
import com.google.android.gms.ads.InterstitialAd
with the new one:
import com.google.android.gms.ads.interstitial.InterstitialAd
2.Replace the old initialization:
interstitialAd = InterstitialAd(requireContext())
interstitialAd.adUnitId = "ca-app-pub-00000000/11111111"
interstitialAd.loadAd(AdRequest.Builder().build())
with the new one:
val adRequest = AdRequest.Builder().build()
InterstitialAd.load(requireContext(),
"ca-app-pub-00000000/11111111",
adRequest,
object : InterstitialAdLoadCallback() {
override fun onAdLoaded(myAd: InterstitialAd) {
Timber.d("Ad Loaded")
interstitialAd = myAd
}
override fun onAdFailedToLoad(adError: LoadAdError) {
Timber.d("Failed to load ad: ${adError.message}")
interstitialAd = null
}
})
3.Replace the old way of showing it:
if (interstitialAd.isLoaded) {
interstitialAd.show()
} else {
Timber.d("Ad wasn't loaded yet!")
}
with the new one:
if (interstitialAd != null){
interstitialAd?.show(requireActivity())
}else {
Timber.d("Interstitial Ad not ready yet")
}
4.There is no step 4, enjoy😁
Source
public static com.google.android.gms.ads.interstitial.InterstitialAd googleFullscreen;
public static void mLoadGoogleFullScreenAds(final Activity activity) {
FullScreenContentCallback fullScreenContentCallback = new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
googleFullscreen = null;
// Proceed to the next level.
}
#Override
public void onAdShowedFullScreenContent() {
super.onAdShowedFullScreenContent();
}
#Override
public void onAdFailedToShowFullScreenContent(com.google.android.gms.ads.AdError adError) {
super.onAdFailedToShowFullScreenContent(adError);
Log.d(TAG, "onAdFailedToShowFullScreenContent: " + adError.toString());
}
};
googleFullscreen.load(
activity,
activity.getResources().getString(R.string.google_fullscreen),
new AdRequest.Builder().build(),
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd ad) {
googleFullscreen = ad;googleFullscreen.setFullScreenContentCallback(fullScreenContentCallback);
googleFullscreen.show(activity);
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError adError) {
googleFullscreen = null;
Log.d(TAG, "onAdFailedToLoad: " + adError.toString());
// Code to be executed when an ad request fails.
}
});
}
i think this code solve your problem

Why App Open Ads runs before MainActivity?

I'm asking why after I placed the App Open Ads in the AppOpenManager and some other code added on MyApplication same article that Google Admob advices to use but I'm still confused, Why when I launch my app:
The Splash screen : Open First
Then the App Open Ads opens and stay running in the background while the MainActivity opens above the App Open Ads.
If you know how to solve this help me please...
Thanks in advance.
Here is the GIF about the app I was using for the test to show you App Open Ads
Try this:
gradle:
implementation 'com.google.android.gms:play-services-ads:20.1.0'
def lifecycle_version = "2.2.0"
def lifecycle_version1 = "2.3.1"
implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version1"
annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version1"
Manifests
android:name=".MyApplication"
AppOpenManager.java
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.util.Log;
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.appopen.AppOpenAd;
import java.util.Date;
import static androidx.lifecycle.Lifecycle.Event.ON_START;
public class AppOpenManager implements LifecycleObserver, Application.ActivityLifecycleCallbacks {
private long loadTime = 0;
private static final String LOG_TAG = "AppOpenManager";
private static String AD_UNIT_ID = "abc";
private AppOpenAd appOpenAd = null;
private Activity currentActivity;
private AppOpenAd.AppOpenAdLoadCallback loadCallback;
private static boolean isShowingAd = false;
private final MyApplication myApplication;
/** Constructor */
public AppOpenManager(MyApplication myApplication) {
this.myApplication = myApplication;
this.AD_UNIT_ID = myApplication.getString(R.string.app_open_id);
this.myApplication.registerActivityLifecycleCallbacks(this);
ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
}
/** LifecycleObserver methods */
#OnLifecycleEvent(ON_START)
public void onStart() {
showAdIfAvailable();
Log.d(LOG_TAG, "onStart");
}
/** Request an ad */
public void fetchAd() {
// Have unused ad, no need to fetch another.
if (isAdAvailable()) {
return;
}
loadCallback =
new AppOpenAd.AppOpenAdLoadCallback() {
/**
* Called when an app open ad has loaded.
*
* #param ad the loaded app open ad.
*/
#Override
public void onAdLoaded(AppOpenAd ad) {
AppOpenManager.this.appOpenAd = ad;
AppOpenManager.this.loadTime = (new Date()).getTime();
}
/**
* Called when an app open ad has failed to load.
*
* #param loadAdError the error.
*/
#Override
public void onAdFailedToLoad(LoadAdError loadAdError) {
// Handle the error.
}
};
AdRequest request = getAdRequest();
AppOpenAd.load(
myApplication, AD_UNIT_ID, request,
AppOpenAd.APP_OPEN_AD_ORIENTATION_PORTRAIT, loadCallback);
}
/** Creates and returns ad request. */
private AdRequest getAdRequest() {
return new AdRequest.Builder().build();
}
/** Utility method to check if ad was loaded more than n hours ago. */
private boolean wasLoadTimeLessThanNHoursAgo(long numHours) {
long dateDifference = (new Date()).getTime() - this.loadTime;
long numMilliSecondsPerHour = 3600000;
return (dateDifference < (numMilliSecondsPerHour * numHours));
}
/** Utility method that checks if ad exists and can be shown. */
public boolean isAdAvailable() {
return appOpenAd != null && wasLoadTimeLessThanNHoursAgo(4);
}
/** ActivityLifecycleCallback methods */
#Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {}
#Override
public void onActivityStarted(Activity activity) {
currentActivity = activity;
}
#Override
public void onActivityResumed(Activity activity) {
currentActivity = 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) {
currentActivity = null;
}
/** Shows the ad if one isn't already showing. */
public void showAdIfAvailable() {
// Only show ad if there is not already an app open ad currently showing
// and an ad is available.
if (!isShowingAd && isAdAvailable()) {
Log.d(LOG_TAG, "Will show ad.");
FullScreenContentCallback fullScreenContentCallback =
new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
// Set the reference to null so isAdAvailable() returns false.
AppOpenManager.this.appOpenAd = null;
isShowingAd = false;
fetchAd();
}
#Override
public void onAdFailedToShowFullScreenContent(AdError adError) {}
#Override
public void onAdShowedFullScreenContent() {
isShowingAd = true;
}
};
appOpenAd.show(currentActivity);
} else {
Log.d(LOG_TAG, "Can not show ad.");
fetchAd();
}
}
}
MyApplication.java
import android.app.Application;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
/** The Application class that manages AppOpenManager. */
public class MyApplication extends Application {
private static AppOpenManager appOpenManager;
#Override
public void onCreate() {
super.onCreate();
MobileAds.initialize(
this,
new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {}
});
appOpenManager = new AppOpenManager(this);
}
}
As Google have mentioned in "Cold starts and loading screens" Section here, app open ads will show when users foreground the app when it's suspended in memory. "Cold starts" occur when the app is launched but was not previously suspended in memory.
What we should do is avoid using System.exit(0) in onBackPressed() for exiting the app since it will make the app in Cold starts mode when opened. Just use finishAffinity() for exiting the app.
replace this
#OnLifecycleEvent(ON_START)
public void onStart() {
showAdIfAvailable();
}
with this
#OnLifecycleEvent(ON_START)
public void onStart() {
if (!(currentActivity instanceof SplashActivity)) {
showAdIfAvailable();
}
}

Google AdMob ads not showing in Unity

I am making a Flappy Bird game and trying to display ads when the Bird dies.
I have setup Google AdMob and UnityAds from Google AdMob Console and Unity Dashboard respectively.
This is my code below.
using GoogleMobileAds.Api;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class GameController : MonoBehaviour {
public static GameController instance;
public GameObject gameOverText;
public bool isGameOver = false;
public float scrollSpeed = -1.5f;
public Text scoreText;
private int score = 0;
private InterstitialAd interstitialAd;
// Awake is called before Start
void Awake() {
if(instance == null) {
instance = this;
} else if (instance != null) {
Destroy(gameObject);
}
}
// Start is called before the first frame update
void Start() {
MobileAds.Initialize(initStatus => { });
RequestInterstitial();
}
private void RequestInterstitial() {
string adUnitId = "unexpected_platform";
#if UNITY_ANDROID
adUnitId = Values.TEST_ANDROID_AD_UNIT_ID;
#endif
// Initialize InterstitialAd
this.interstitialAd = new InterstitialAd(adUnitId);
// Create empty ad request
AdRequest request = new AdRequest.Builder().Build();
// Load interstitial with the request
this.interstitialAd.LoadAd(request);
}
public void ShowAd() {
if (this.interstitialAd.IsLoaded()) {
this.interstitialAd.Show();
}
}
// Update is called once per frame
void Update() {
if(isGameOver && Input.GetKey(KeyCode.Space)) {
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
} else if (isGameOver && Input.touchCount > 0) {
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
public void BirdScored() {
if(isGameOver) {
return;
}
score++;
scoreText.text = "Score: " + score;
}
public void BirdDied() {
gameOverText.SetActive(true);
isGameOver = true;
ShowAd();
}
}
The code reaches the ShowAd() function when I debug but the ad is not displayed.
What am I doing wrong?

Application Class in IOS Swift

In android, you can define a class and extend with "Application" class. In this class you can declare app level fields and methods. In this class you also have access to the Application Context and there is a method which is invoked on the start of application. Sample of this is given below:
public class App extends Application {
private static Context sContext;
private static InterstitialAd mInterstitialAd;
public static Context getAppContext() {
return sContext;
}
public static InterstitialAd getInterstitialAd() {
return mInterstitialAd;
}
#Override
public void onCreate() {
super.onCreate();
sContext = getApplicationContext();
MobileAds.initialize(this, sContext.getString(R.string.ADMOB_APP_ID));
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(sContext.getString(R.string.interstitial));
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
});
}
}
What is corresponding thing in IOS?
In iOS, You can do configuration inside AppDelegate File in below method.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
//Here You Can Configure
return true
}
You can define class level methods in separate file in iOS and you can call it in didFinishLaunchingWithOptions() in AppDelegate file.

RxJava with multi network request

Here is the code:
public class HomeDetails extends Model {
public Home mHomeData;
public AD mAdData;
public HomeDetails(Api api, String url) {
api.getHome(url, createHome(), this);
api.getAd(url, createAD(), this);
}
private NetworkResponse.Listener<Home> createHome() {
return new NetworkResponse.Listener<Home>() {
#Override
public void onResponse(Home home) {
mHomeData = home;
}
};
}
private NetworkResponse.Listener<AD> createAD() {
return new NetworkResponse.Listener<AD>() {
#Override
public void onResponse(AD ad) {
mAdData = ad;
}
};
}
}
I'd like to use RxJava to help me to know when the two requests are all done. if all is done, then execute another method.
You can use Observable.create() to create the two observable for the two network calls, then you can concat() or zip() them and execute whatever you want in the onNext().

Categories

Resources