在App Purchase中使用boolean删除广告

时间:2016-08-17 06:36:19

标签: android in-app-purchase

我试图在app app中实施Android删除广告功能。在我的班级下,我把private boolean isAdsDisabled;放在onCreate下,我把

if (isAdsDisabled) {
            AdView adView = (AdView) this.findViewById(R.id.adView);
            adView.setVisibility(View.GONE);
        } else {
            AdView adView = (AdView) this.findViewById(R.id.adView);
            AdRequest adRequest = new AdRequest.Builder().build();
            adView.loadAd(adRequest);
        }

这是我的OnIabPurchaseFinishedListener

IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener
            = new IabHelper.OnIabPurchaseFinishedListener() {
        public void onIabPurchaseFinished(IabResult result,
                                          Purchase purchase)
        {
            if (result.isFailure()) {
                // Handle error
                return;
            }
            else if (purchase.getSku().equals(ITEM_SKU)) {
                removeAds();
            }

        }
    };

我的removeAds()

private void removeAds() {
        AdView adView = (AdView) this.findViewById(R.id.adView);
        adView.setVisibility(View.GONE);
        isAdsDisabled = true;
    }

成功购买后,我设法隐藏广告。但是,重新启动应用后,问题再次出现。好像它不能保存布尔值isAdsDisabled = true。如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

使用SharedPreferences解决了这个问题。

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        boolean isAdsDisabled = settings.getBoolean("isAdsDisabled", false);

        if (isAdsDisabled) {
            AdView adView = (AdView) this.findViewById(R.id.adView);
            adView.setVisibility(View.GONE);
        } else {
            AdView adView = (AdView) this.findViewById(R.id.adView);
            AdRequest adRequest = new AdRequest.Builder().build();
            adView.loadAd(adRequest);
        }

我的removeAds()

private void removeAds() {
        AdView adView = (AdView) this.findViewById(R.id.adView);
        adView.setVisibility(View.GONE);
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean("isAdsDisabled", true);
        editor.commit();
    }