googleads-mobile-unity: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.app.KeyguardManager.isDeviceLocked()' on a null object reference

[REQUIRED] Step 1: Describe your environment

  • Unity version: 2020.3.30f1
  • Google Mobile Ads Unity plugin version: 8.6.0
  • Plugin installation method: .unitypackage import
  • Platform: Android
  • Platform OS version: All android versions
  • Any specific devices issue occurs on: Google Pixel 7a, Samsung Galaxy S21 5G
  • Mediation ad networks used, and their versions: None

[REQUIRED] Step 2: Describe the problem

Started seeing high crash rates (2-3%) at the beginning of last month on google play console which has been slowly going up and as at October 31st was now at 50%, so i had to remove admob ads and started working on the issue locally. I didn’t change anything on my end. I started testing my game locally with test ads and i discovered that once a bannner ad gets requested with the LoadAd() function, it shows a black banner with “test ads” tag and then the game crashes. Same thing happens for rewarded ads. THE CRASH SEEMS TO ONLY OCCUR ON INSTANT PLAY VERSIONS OF MY GAME.

Steps to reproduce:

Import the Google Mobile ads package and the Google Play Instant plugin into a project, build an instant play version and request an ad. Stack trace java.lang.NullPointerException: Attempt to invoke virtual method ‘boolean android.app.KeyguardManager.isDeviceLocked()’ on a null object reference at com.google.android.gms.ads.omid.library.walking.e.run(:com.google.android.gms.policy_ads_fdr_dynamite@243799214@243799204017.685849251.685849251:615) at android.os.Handler.handleCallback(Handler.java:959) at android.os.Handler.dispatchMessage(Handler.java:100) at android.os.Looper.loopOnce(Looper.java:232) at android.os.Looper.loop(Looper.java:317) at android.app.ActivityThread.main(ActivityThread.java:8705) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:580) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:886)

using UnityEngine; using GoogleMobileAds.Api; using System.Collections; using System.Collections.Generic; using System; using System.Threading.Tasks; using PimDeWitte.UnityMainThreadDispatcher;

public class GoogleMobileAdsBanner : MonoBehaviour { public int adTime = 5; private BannerView _bannerView; private bool _isInitialized = false;

#if UNITY_ANDROID
    private string _adUnitId = "ca-app-pub-3940256099942544/6300978111";
#elif UNITY_IPHONE
    private string _adUnitId = "ca-app-pub-3940256099942544/2934735716";
#else
    private string _adUnitId = "unused";
#endif

public void Start()
{   
  UnityMainThreadDispatcher.Instance().Enqueue(() => {
    // Initialize Mobile Ads first
    MobileAds.Initialize(initStatus => {
        _isInitialized = true;
        Debug.Log("Mobile Ads initialized successfully");
        // Start coroutine for delayed ad loading only after initialization
        StartCoroutine(WaitForAd());
    });
  });
}

IEnumerator WaitForAd()
{
    yield return new WaitForSeconds(adTime);
    
    if (!_isInitialized)
    {
        Debug.LogError("Attempted to load ad before Mobile Ads SDK was initialized");
        yield break;
    }

    try
    {
        // Ensure we're on the main thread using UnityMainThreadDispatcher
        UnityMainThreadDispatcher.Instance().Enqueue(() => {
            try
            {
                LoadAd();
            }
            catch (Exception ex)
            {
                Debug.LogError($"Error loading ad: {ex.Message}\n{ex.StackTrace}");
            }
        });
    }
    catch (Exception ex)
    {
        Debug.LogError($"Error enqueueing ad load: {ex.Message}\n{ex.StackTrace}");
    }
}

public void CreateBannerView()
{
    if (!_isInitialized)
    {
        Debug.LogError("Attempted to create banner before Mobile Ads SDK was initialized");
        return;
    }

    Debug.Log("Creating banner view.");

    try
    {
        // If we already have a banner, destroy the old one.
        if(_bannerView != null)
        {
            DestroyAd();
        }

        // Create a 320x50 banner at top of the screen.
        _bannerView = new BannerView(_adUnitId, AdSize.Banner, AdPosition.Top);

        // Listen to events the banner may raise.
        /*ListenToAdEvents();*/

        Debug.Log("Banner view created.");
    }
    catch (Exception ex)
    {
        Debug.LogError($"Error creating banner view: {ex.Message}\n{ex.StackTrace}");
    }
}

public void LoadAd()
{
    if (!_isInitialized)
    {
        Debug.LogError("Attempted to load ad before Mobile Ads SDK was initialized");
        return;
    }

    try
    {
        // Create an instance of a banner view first.
        if(_bannerView == null)
        {
            CreateBannerView();
        }

        // Create our request used to load the ad.
        var adRequest = new AdRequest();

        // Send the request to load the ad.
        Debug.Log("Loading banner ad.");
        _bannerView.LoadAd(adRequest);
    }
    catch (Exception ex)
    {
        Debug.LogError($"Error loading ad: {ex.Message}\n{ex.StackTrace}");
    }
}

public void ShowAd()
{
    if (_bannerView != null)
    {
        _bannerView.Show();
    }
    else
    {
        Debug.LogWarning("Banner view is not initialized");
    }
}

public void HideAd()
{
    if (_bannerView != null)
    {
        _bannerView.Hide();
    }
}

public void DestroyAd()
{
    if (_bannerView != null)
    {
        Debug.Log("Destroying banner view.");
        _bannerView.Destroy();
        _bannerView = null;
    }
}
// TODO(you): code here to reproduce the problem

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 20 (6 by maintainers)

Most upvoted comments

Update: We have identified the issue and are looking into a fix. We do not have a workaround at the moment.

@dipupo6 Hi, I was out on vacation so thanks for waiting. This issue may be related to using instant play. I found this older guide which can help. It says we need to use the lite SDK for instant apps. Please give it a look and let me know if it helps:

https://developers.google.com/admob/android/instant-apps

I’ve tried a lot of things including that, it doesn’t help. The support team got back to me today and said the issue is under investigation, but I don’t know how long it’s going to take for the issue to be fixed.

Can you please file a bug ticket with Admob Support, I will most likely need to get the Android team involved in this. I will see if I can replicate this on my end.

I’ve done that. Hopefully, this gets resolved as soon as possible.

Can you please file a bug ticket with Admob Support, I will most likely need to get the Android team involved in this. I will see if I can replicate this on my end.