为什么我会得到'必须在主UI线程上调用setAdListener'当我在UI线程上运行它时

时间:2016-08-16 15:51:46

标签: android admob

我正在尝试将插页式广告添加到我的游戏中。它建立在书籍的框架之上。构造函数是:

 public GameScreen(Game game) {
        super(game);
        world = new World();
        clueLetters = new String[10];
        levelNo = SettingsObject.levelUnlock;
        getWord();
        interstitialAd = new InterstitialAd(AndroidGame.context);
        interstitialAd.setAdUnitId("ca-app-pub-1861496496821617/");

        //Create an ad request
        AdRequest.Builder adRequestBuilder = new AdRequest.Builder();

        AndroidGame.activityReference.runOnUiThread(new Runnable() {
            @Override
            public void run()

            {
                // Set AdListener
                interstitialAd.setAdListener(new AdListener() {
                    @Override
                    public void onAdClosed() {
                        super.onAdClosed();
                    }
                });
            }
        });

        Looper.prepare();
        interstitialAd.loadAd(adRequestBuilder.build());

    }

然而,我收到错误:

 java.lang.IllegalStateException: setAdListener must be called on the main UI thread.

你能告诉我为什么我会收到这个错误以及如何修复它吗?

1 个答案:

答案 0 :(得分:4)

我使用类似/相同的框架。最好的方法是在AndroidGame活动类中设置插页式广告,并使用界面在游戏屏幕中显示广告:

首先创建接口类:

public interface MyActivityListener {
    public void showInterstitial();
}

然后在您的AndroidGame类中,实现界面:

public abstract class AndroidGame extends Activity implements Game, MyActivityListener {
  @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        interstitialAd = new InterstitialAd(AndroidGame.context);
        interstitialAd.setAdUnitId("ca-app-pub-1861496496821617/");
        //Create an ad request
        AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
        interstitialAd.loadAd(adRequestBuilder.build());

                // Set AdListener
                interstitialAd.setAdListener(new AdListener() {
                    @Override
                    public void onAdClosed() {
                        super.onAdClosed();
                    }
                });
        }

@Override
    public void showInterstitial() {
        runOnUiThread(new Runnable() {   
            @Override
            public void run() {
                if(interstitialAd != null && interstitialAd.isLoaded())
                   interstitialAd.show();       
            }
        });

    }
}

这样,只要您想在任何screen中展示广告,就可以调用showInterstitial()方法。 游戏屏幕中的示例:

public class GameScreen extends Screen{
    MYActivityListener mL;
public GameScreen(Game game) {
        super(game);
        mL = (MyActivityListener)game;
        world = new World();
        clueLetters = new String[10];
        levelNo = SettingsObject.levelUnlock;
        getWord();
        mL.showInterstitial();
    }

}

我使用此实现来完成需要在UI线程上运行的所有工作(隐藏和显示横幅广告,评分/分享应用,存储分数等。希望它有所帮助:)