Showing admob interstitial in non-activity class

2019-08-23 06:25发布

问题:

In my game, I have a class which constructs the Gameview and allows the user to play various levels till he want. Now I want to show an admob interstitial when the level is over. This class GameView.java has method to start the game initially which is invoked from the main activity.

The admob interstitial code requires activity instance as the first argument. So I passed an instance of main activity (using this keyword) to the play method of GameView but I get the following exception on invoking the interstitial code:

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

My code in GameView.java is:

  InterstitialAd interstitial = new InterstitialAd((MainActivity)mContext,
        "admobunitid");
// Create ad request

AdRequest adRequest = new AdRequest();
// Begin loading your interstitial
interstitial.loadAd(adRequest);
interstitial.setAdListener((MainActivity)mContext);

GameView.java doesn't extend any class and doesn't implement any interface as of now. Any help on this?

回答1:

You're calling it from a worker thread. You need to call from within the main thread. You could use a handler, for example.

 activity.runOnUiThread(new Runnable() {
      public void run() {
        InterstitialAd interstitial = new InterstitialAd((MainActivity)mContext,
        "admobunitid");
// Create ad request

AdRequest adRequest = new AdRequest();
// Begin loading your interstitial
interstitial.loadAd(adRequest);
interstitial.setAdListener((MainActivity)mContext);
      }
    });


回答2:

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

This usually happens when you try to show a Dialog from outside the Main Thread.

Try to wrap that code inside a Runnable and then execute it using MainActivity.runOnUiThread();



回答3:

Are there any contraindications of using interfaces? Because using them in this case would be resonable.



回答4:

This is not Activity Class then you need to call within runOnUiThread. Like it is android asynctask class doBackground method then you need to call like this.

activity/context.runOnUiThread(new Runnable() {
  public void run() {
    /// your Ui view amd message
InterstitialAd interstitial = new InterstitialAd((MainActivity)mContext,
        "admobunitid");
// Create ad request

AdRequest adRequest = new AdRequest();
// Begin loading your interstitial
interstitial.loadAd(adRequest);
interstitial.setAdListener((MainActivity)mContext);
  }
});

Thanks



标签: android admob