Showing admob interstitial in non-activity class

2019-08-23 05:34发布

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?

标签: android admob
4条回答
倾城 Initia
2楼-- · 2019-08-23 06:27

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

查看更多
Root(大扎)
3楼-- · 2019-08-23 06:31
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();

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-08-23 06:35

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);
      }
    });
查看更多
爷的心禁止访问
5楼-- · 2019-08-23 06:35

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

查看更多
登录 后发表回答