I am working on an iOS app with Unity 2019.2.21f1. I set up an adMob account about two months ago, and had gotten banner ads and interstitial ads to show successfully in my app shortly after that.
Then, about a week ago, the ads stopped showing up. I'm not sure if I unwittingly changed something in my code/admob configuration, or if there is something else going on here...
This is my script for managing AdMob ads:
using System;
using UnityEngine;
using GoogleMobileAds.Api;
public class AdBannerScriptAdMob : MonoBehaviour
{
private BannerView bannerView;
private InterstitialAd interstitialAd;
private MainPlayer mainPlayer;
int previousMod;
public bool bHasRequestedInterstitialAd;
public bool bHasShownInterstitialAd;
public bool bHasActiveNoAdsSubcription;
public void Start()
{
bHasRequestedInterstitialAd = false;
bHasShownInterstitialAd = false;
bHasActiveNoAdsSubcription = false;
mainPlayer = GameObject.FindObjectOfType<MainPlayer>();
#if UNITY_ANDROID
string appId = "ca-app-pub-3940256099942544~3347511713";
#elif UNITY_IPHONE
string appId = "ca-app-pub-xxxxxxxxxxxxxxxx~xxxxxxxxxx";
#else
string appId = "unexpected_platform";
#endif
// Initialize the Google Mobile Ads SDK.
MobileAds.Initialize(appId);
this.RequestBanner();
}
private AdRequest CreateAdRequest()
{
return new AdRequest.Builder()
.AddKeyword("game")
.SetGender(Gender.Male)
.SetBirthday(new DateTime(1985, 1, 1))
.TagForChildDirectedTreatment(false)
.AddExtra("color_bg", "9B30FF")
.Build();
}
public void Update()
{
// Debug.Log("printing mainPlayer.iNumBalls from AdBannerScriptAdMob: " + mainPlayer.iNumBalls);
if ((mainPlayer.iNewNumBalls+10) %20 == 0 && !bHasActiveNoAdsSubcription)
{
if (!bHasRequestedInterstitialAd)
{
Debug.Log("Should be requesting InterstitialAd now");
RequestInterstitial();
bHasRequestedInterstitialAd = true;
bHasShownInterstitialAd = false;
}
}
if ((mainPlayer.iNumBalls) % 20 < previousMod)
{
if (!bHasShownInterstitialAd && !bHasActiveNoAdsSubcription)
{
Debug.Log("Trying to show InterstitialAd now");
this.ShowInterstitial();
bHasShownInterstitialAd = true;
bHasRequestedInterstitialAd = false;
}
}
previousMod = (int)mainPlayer.iNumBalls % 20;
}
private void ShowInterstitial()
{
if (this.interstitialAd.IsLoaded())
{
Debug.Log("InterstitialAd is ready and should be showing now");
this.interstitialAd.Show();
}
else
{
Debug.Log("Interstitial is not ready yet");
}
}
private void RequestInterstitial()
{
// These ad units are configured to always serve test ads.
#if UNITY_EDITOR
string adUnitId = "unused";
#elif UNITY_ANDROID
string adUnitId = "ca-app-pub-3940256099942544/1033173712";
#elif UNITY_IPHONE
string adUnitId = "ca-app-pub-xxxxxxxxxxxxxxxx/xxxxxxxxxx"; //real ID from my admob account
#else
string adUnitId = "unexpected_platform";
#endif
// Clean up interstitial ad before creating a new one.
if (this.interstitialAd != null)
{
this.interstitialAd.Destroy();
}
// Create an interstitial.
this.interstitialAd = new InterstitialAd(adUnitId);
// Register for ad events.
this.interstitialAd.OnAdLoaded += this.HandleInterstitialLoaded;
this.interstitialAd.OnAdFailedToLoad += this.HandleInterstitialFailedToLoad;
this.interstitialAd.OnAdOpening += this.HandleInterstitialOpened;
this.interstitialAd.OnAdClosed += this.HandleInterstitialClosed;
this.interstitialAd.OnAdLeavingApplication += this.HandleInterstitialLeftApplication;
// Load an interstitial ad.
this.interstitialAd.LoadAd(this.CreateAdRequest());
}
private void RequestBanner()
{
#if UNITY_ANDROID
string adUnitId = "ca-app-pub-3940256099942544/6300978111";
#elif UNITY_IPHONE
string adUnitId = "ca-app-pub-xxxxxxxxxxxxxxxx/xxxxxxxxxx"; //real ID from my admob account
#else
string adUnitId = "unexpected_platform";
#endif
//AdSize adSize = new AdSize(250, 250);
//adSize = AdSize.Banner;
AdSize adSize = AdSize.SmartBanner;
// Create a banner at the bottom of the screen.
this.bannerView = new BannerView(adUnitId, adSize, AdPosition.Bottom);
// Called when an ad request has successfully loaded.
this.bannerView.OnAdLoaded += this.HandleOnAdLoaded;
// Called when an ad request failed to load.
this.bannerView.OnAdFailedToLoad += this.HandleOnAdFailedToLoad;
// Called when an ad is clicked.
this.bannerView.OnAdOpening += this.HandleOnAdOpened;
// Called when the user returned from the app after an ad click.
this.bannerView.OnAdClosed += this.HandleOnAdClosed;
// Called when the ad click caused the user to leave the application.
this.bannerView.OnAdLeavingApplication += this.HandleOnAdLeavingApplication;
// Create an empty ad request.
AdRequest request = new AdRequest.Builder().Build();
// Load the banner with the request.
this.bannerView.LoadAd(request);
}
public void HandleOnAdLoaded(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdLoaded event received");
}
public void HandleOnAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
MonoBehaviour.print("HandleFailedToReceiveAd event received with message: "
+ args.Message);
}
public void HandleOnAdOpened(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdOpened event received");
}
public void HandleOnAdClosed(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdClosed event received");
}
public void HandleOnAdLeavingApplication(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdLeavingApplication event received");
}
#region Interstitial callback handlers
public void HandleInterstitialLoaded(object sender, EventArgs args)
{
MonoBehaviour.print("HandleInterstitialLoaded event received");
}
public void HandleInterstitialFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
MonoBehaviour.print("HandleInterstitialFailedToLoad event received with message: " + args.Message);
}
public void HandleInterstitialOpened(object sender, EventArgs args)
{
MonoBehaviour.print("HandleInterstitialOpened event received");
}
public void HandleInterstitialClosed(object sender, EventArgs args)
{
MonoBehaviour.print("HandleInterstitialClosed event received");
}
public void HandleInterstitialLeftApplication(object sender, EventArgs args)
{
MonoBehaviour.print("HandleInterstitialLeftApplication event received");
}
#endregion
}
When running the app via Xcode on my physical iOS device (iPhone 8, iOS 13.3.1), I get the following messages in the Xcode console:
HandleFailedToReceiveAd event received with message: Failed to receive ad with error: (null)
and
HandleInterstitialFailedToLoad event received with message: Failed to receive ad with error: (null)
I have verified and reverified that string appId (in method Start()) and both instances of string adUnitId in the methods RequestInterstitial() and RequestBanner() match the IDs from my adMob account. My adMob account shows the following status:
At this point, I am unsure what caused the ads to stop showing up. Internet connectivity on the mobile device is verified to be working.
Additional note: After having written this question, and before posting it, I tested my application repeatedly, and weirdly enough, one time, the interstitial did show up correctly. However, the remaining ~100 times, the interstitial did not show up at all, as described in this post. The banner ad still has not shown up at all. To my mind, this doesn't make the possible issue any clearer, but maybe it sheds some light on the issue for someone else?
Related
I am trying to add Google Play Services to my Xamarin Android app.
I am using Play Games Services v2 SDK and trying to follow this tutorial from the Official documentation.
The Java code for signing in would be that:
GamesSignInClient gamesSignInClient = PlayGames.getGamesSignInClient(getActivity());
gamesSignInClient.isAuthenticated().addOnCompleteListener(isAuthenticatedTask -> {
boolean isAuthenticated =
(isAuthenticatedTask.isSuccessful() &&
isAuthenticatedTask.getResult().isAuthenticated());
if (isAuthenticated) {
// Continue with Play Games Services
} else {
// Disable your integration with Play Games Services or show a
// login button to ask players to sign-in. Clicking it should
// call GamesSignInClient.signIn().
}
});
How can I translate it to C#?
Anyone can help me please?
This is my best attempt, but I am getting an exception on SetJniIdentityHashCode method not implemented.
using Android.Gms.Games;
using Android.Gms.Tasks;
// ...
PlayGamesSdk.Initialize(this);
IGamesSignInClient gamesSignInClient = PlayGames.GetGamesSignInClient(this);
gamesSignInClient.IsAuthenticated().AddOnCompleteListener(
new OnCompleteListener()
);
// ...
public class OnCompleteListener : Java.Lang.Object, IOnCompleteListener
{
public void Disposed()
{
throw new NotImplementedException();
}
public void DisposeUnlessReferenced()
{
throw new NotImplementedException();
}
public void Finalized()
{
throw new NotImplementedException();
}
public void OnComplete(Task task)
{
//var isAuthenticated =
// (task.IsSuccessful &&
// ((????)task.Result).isAuthenticated())
//if (isAuthenticated)
//{
// // Continue with Play Games Services
//}
//else
//{
// // Disable your integration with Play Games Services or show a
// // login button to ask players to sign-in. Clicking it should
// // call GamesSignInClient.signIn().
//}
}
public void SetJniIdentityHashCode(int value)
{
throw new NotImplementedException();
}
public void SetJniManagedPeerState(JniManagedPeerStates value)
{
throw new NotImplementedException();
}
public void SetPeerReference(JniObjectReference reference)
{
throw new NotImplementedException();
}
}
I managed to get the authentication result in the following way, probably was just using the wrong references.
public class TaskCompleteListener : Java.Lang.Object, IOnCompleteListener
{
public void OnComplete(Android.Gms.Tasks.Task task)
{
var isAuthenticated = task.IsSuccessful &&
((AuthenticationResult)task.Result).IsAuthenticated;
if (isAuthenticated)
{
// Continue with Play Games Services
}
else
{
// Disable your integration with Play Games Services or show a
// login button to ask players to sign-in. Clicking it should
// call GamesSignInClient.signIn().
}
}
}
I'm trying to integrate IronSource ads into my Unity Project. When I build my app, open it in XCode and run it on my iPhone 6s for testing, I get a message telling me that the IronSource API hasn't got an Interstitial.
The Error Message is:
"(DATE) AdManager(<- The Name of my Script) [ironSource SDK] API: IronSource: hasINterstitial false"
Also, the Interstitial Ad does not initialize. So "IronSource.Agent.isInterstitialReady()" stays false.
What am I doing wrong?
I have imported the SDK and I wrote this Script (C#):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AdManager : MonoBehaviour
{
private string AppKey = "MY_APP_ID";
void Start()
{
Invoke("InitInterstitial", 4);
}
#region interstitial
private void InitInterstitial()
{
IronSource.Agent.init(AppKey, IronSourceAdUnits.INTERSTITIAL);
while (!IronSource.Agent.isInterstitialReady()) { Debug.Log("Initializing..."); }
Debug.Log("Initialized!");
IronSource.Agent.loadInterstitial();
Debug.Log("Loaded!");
}
void OnEnable()
{
IronSourceEvents.onInterstitialAdReadyEvent += InterstitialAdReadyEvent;
IronSourceEvents.onInterstitialAdLoadFailedEvent += InterstitialAdLoadFailedEvent;
IronSourceEvents.onInterstitialAdShowSucceededEvent += InterstitialAdShowSucceededEvent;
IronSourceEvents.onInterstitialAdShowFailedEvent += InterstitialAdShowFailedEvent;
IronSourceEvents.onInterstitialAdClickedEvent += InterstitialAdClickedEvent;
IronSourceEvents.onInterstitialAdOpenedEvent += InterstitialAdOpenedEvent;
IronSourceEvents.onInterstitialAdClosedEvent += InterstitialAdClosedEvent;
}
//Invoked when the initialization process has failed.
//#param description - string - contains information about the failure.
void InterstitialAdLoadFailedEvent(IronSourceError error)
{
Debug.LogError("ERROR!!__: " + error);
}
//Invoked right before the Interstitial screen is about to open.
void InterstitialAdShowSucceededEvent()
{
}
//Invoked when the ad fails to show.
//#param description - string - contains information about the failure.
void InterstitialAdShowFailedEvent(IronSourceError error)
{
}
// Invoked when end user clicked on the interstitial ad
void InterstitialAdClickedEvent()
{
}
//Invoked when the interstitial ad closed and the user goes back to the application screen.
void InterstitialAdClosedEvent()
{
}
//Invoked when the Interstitial is Ready to shown after load function is called
void InterstitialAdReadyEvent()
{
Debug.Log("_______READY!_____");
}
//Invoked when the Interstitial Ad Unit has opened
void InterstitialAdOpenedEvent()
{
}
public void ShowInterstitial()
{
IronSource.Agent.showInterstitial();
}
#endregion
}
(The Debug.Logs are only for debugging my problem)
Thanks for your Help!
It looks like the while loop never ends.
The function that actually triggers the ad request is:
IronSource.Agent.loadInterstitial();
Try to do the following:
private void InitInterstitial()
{
IronSource.Agent.init(AppKey, IronSourceAdUnits.INTERSTITIAL);
Debug.Log("Initializing..."); }
IronSource.Agent.loadInterstitial();
}
//Invoked when the Interstitial is Ready to shown after load function is called
void InterstitialAdReadyEvent()
{
Debug.Log("Ad Loaded");
}
I have went through the Xamarin IAB 'tutorial' on it's Component page. I installed the component and Google Play Billing Lib into my app, published my apk to Google Play Dev Console in Alpha and added products on the Dev Console to the app. However, when I try to test the app on a phone, anytime I click on any of the purchase buttons nothing happens. The buttons themselves worked fine I have tested them by pushing other notifications, changing colors, etc. They work with everything else, but when it comes to purchasing nothing happens, no pop-ups, no buffering or attempt to connection, literally nothing. I think my app never connects to Google Play, and I have no idea why.
My Main Activity
private InAppBillingServiceConnection _serviceConnection;
private string publicKey = "my public key";
private IList<Product> _products;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Establish Connection to Google Play Store
_serviceConnection = new InAppBillingServiceConnection(this, publicKey);
_serviceConnection.OnConnected += async () =>
{
// Load available products and any purchases
await RequestProducts();
};
// Attempt to connect to the service
_serviceConnection.Connect();
IAPHelper.Instance.Initalize(_products, _serviceConnection);
var g = new Game1();
SetContentView(g.Services.GetService<View>());
g.Run();
}
// Request a list of available products that the user can purchase by providing alist of
protected async Task RequestProducts()
{
_products = await _serviceConnection.BillingHandler.QueryInventoryAsync(new List<string>{
ReservedTestProductIDs.Purchased,
ReservedTestProductIDs.Canceled,
ReservedTestProductIDs.Refunded,
ReservedTestProductIDs.Unavailable
}, ItemType.Product);
// Were any products returned?
if (_products == null)
{
// No, abort
return;
}
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
My Helper Method
private IList<Product> _products;
private InAppBillingServiceConnection _serviceConnection;
public void Initalize(IList<Product> _products, InAppBillingServiceConnection _serviceConnection)
{
this._products = _products;
this._serviceConnection = _serviceConnection;
}
// Called when a product is clicked to buy
public bool ProductPurchasing(string id)
{
Product _selectedProduct = null;
try
{
for (int i = 0; i < _products.Count; i++)
{
if (id == _products[i].ProductId)
{
_selectedProduct = _products[i];
break;
}
}
_serviceConnection.BillingHandler.BuyProduct(_selectedProduct);
return true;
}
catch (Exception ex)
{
return false;
}
}
Hello I have problem with installing AdColony SDK for Unity. I just setup code like in instruction but it still shows that I haven't any ads in my zone. I have no idea if I did something wrong or I forgot to implement something.
public void Initialize()
{
// Assign any AdColony Delegates before calling Configure
AdColony.OnV4VCResult = OnV4VCResult;
// If you wish to use a the customID feature, you should call that now.
// Then, configure AdColony:
AdColony.Configure
(
"version:1.0,store:google",// Arbitrary app version and Android app store declaration.
APPID, // ADC App ID from adcolony.com
zoneID
);
}
public void PlayV4VC(string zoneID, bool prePopup, bool postPopup){
if (AdColony.IsV4VCAvailable (zoneID)) {
Debug.Log ("Video is avaiable!");
} else {
Debug.Log ("Video is NOT avaiable!");
}
}
private void OnV4VCResult (bool success,string name, int amount){
if (success) {
Debug.Log ("Video watched!");
} else {
Debug.Log ("Failed.");
}
}
I am developing one application where i will launch a url in the browser from which i will launch my application.
Suppose if i will click google.com, and press enter, it will launch my application. For that i tried with the HttpFilterRegistry API.
For reference i am using the HTTPFilterDemo application. But currently while launching the app, i am getting the NullPointerException.
I wrote the below code i the openFilter Method:
public Connection openFilter(String name, int mode, boolean timeouts) throws IOException {
Logger.out("Protocol", "it is inside the openFilter method");
_url = name.substring(2);
_requestHeaders = new HttpHeaders();
_responseHeaders = new HttpHeaders();
_responseHeaders.setProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE, "text/html");
Logger.out("Protocol", "here it is come ::::44444444");
final int modHandle = CodeModuleManager.getModuleHandle("AppLaunchBrowser");
Logger.out("Protocol", "here is the module handle:::" + modHandle);
final ApplicationDescriptor[] apDes = CodeModuleManager.getApplicationDescriptors(modHandle);
final ApplicationDescriptor appDescriptor = new ApplicationDescriptor(apDes[0], new String[] {});
Logger.out("Protocol", "here is the app descriptor:::" + appDescriptor);
try {
final int appCode = ApplicationManager.getApplicationManager().runApplication(appDescriptor, true);
Logger.out("Protocol", "here is the app code:::" + appCode);
} catch (ApplicationManagerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// }
return this;
}
And in the application class i am creating alternative entry point and using like below:
public class AppLaunch extends UiApplication{
public static void main(String args[])
{
Logger.out("AppLaunch", args+"length of the arguments::::" +args.length);
if((args != null) && (args.length > 0) && (args[0].equals("background")))
{
Logger.out("AppLaunch", "in the alternate entry point");
// Logger.out("AppLaunch", args+"length of the arguments::::" +args.length);
HttpFilterRegistry.registerFilter("www.google.co.in", "com.innominds.ca", false);
}
else
{
Logger.out("AppLaunch", "Inside the Applaunch");
AppLaunch theApp = new AppLaunch();
theApp.requestForeground();
Logger.out("AppLaunch", "created the app launch object");
theApp.enterEventDispatcher();
// Logger.out("AppLaunch", "in the alternate entry point");
// HttpFilterRegistry.registerFilter("www.google.co.in", "com.innominds.ca", false);
}
}
public AppLaunch()
{
checkPermissions();
showTestScreen();
}
private void checkPermissions()
{
ApplicationPermissionsManager apm = ApplicationPermissionsManager.getInstance();
ApplicationPermissions original = apm.getApplicationPermissions();
if(original.getPermission(ApplicationPermissions.PERMISSION_BROWSER_FILTER) == ApplicationPermissions.VALUE_ALLOW)
{
// All of the necessary permissions are currently available
return;
}
ApplicationPermissions permRequest = new ApplicationPermissions();
permRequest.addPermission(ApplicationPermissions.PERMISSION_BROWSER_FILTER);
boolean acceptance = ApplicationPermissionsManager.getInstance().invokePermissionsRequest(permRequest);
if(acceptance)
{
// User has accepted all of the permissions
return;
}
else
{
}
}
private void showTestScreen()
{
UiApplication.getUiApplication().pushScreen(new AppLaunchScreen());
}
}
Finally i was able to resolve this issue. Actually NPE is coming in some other callback methods because i was implementing the FilterBaseInterface.