更改片段onAdclose。插页式广告

时间:2016-01-10 22:32:31

标签: android asynchronous fragment

我想在广告关闭后更改片段。

但是它抛出了一个IllegalStateException

Fragment1:

...
mInterstitialAd = new InterstitialAd(this.getContext());
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");

mInterstitialAd.setAdListener(new AdListener() {
    @Override
    public void onAdClosed() {
        masterActivity.showGame(); // <---- here comes the error
    }
});
requestNewInterstitial();

// Action Listener on Button show game
Button btnShowGame = (Button) view.findViewById(R.id.btnShowGame);
btnShowGame.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (mInterstitialAd.isLoaded()) {
            mInterstitialAd.show();
        } else {
            masterActivity.showGame();
        }
        return true;
    }
});

MasterActivity:

...
public void showGame() {
    FragmentGameBoard fragment = new FragmentGameBoard();
    fragment.setMasterActivity(this);
    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction transaction = fm.beginTransaction();
    transaction.replace(R.id.contentFragment, fragment);
    transaction.commit();
}

结果如下:

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

从这篇文章看来,错误似乎是正常的: http://www.androiddesignpatterns.com/2013/08/fragment-transaction-commit-state-loss.html

- &GT; &#34;避免在异步回调方法中执行事务。&#34;

但是如何实现我想做的事呢?

这显然与广告和异步逻辑有关。

我不希望用户必须再次点击该按钮来切换片段。

实际

fragment1 -(clickButton)-> interstitialAd -(closeAd)-> fragment1 -(clickButton)-> fragment2

预期

fragment1 -(clickButton)-> interstitialAd -(closeAd)-> fragment2

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

我遇到了同样的问题,并设法解决了以下问题

在showGame()内部更改以下行

而不是:

transaction.commit();

使用:

transaction.commitAllowingStateLoss();