无法在adListener中使用sharedPreference

时间:2019-11-24 17:04:58

标签: java android

我想在用户关闭/离开特定片段时投放插页式广告。为此,我运行了一种方法,在showIntAd()中使用onDetach(),测试广告可以很好地显示
Log.i(TAG, "Ad closed");运行正常,但是如果我尝试使用putIntgetInt,之后的所有代码将无法执行。
基本上我想将int值0保存到我的sharedPreference中,if onAdClosed()运行

创建和加载非页内广告,并在onCreate中启动sharedPreference

        mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        mEditor = mSharedPreferences.edit();

        mInterstitialAd_Arcade = new InterstitialAd(getActivity());
        mInterstitialAd_Arcade.setAdUnitId(getString(R.string.interstitial_ads_test_id));
        AdRequest adRequest = new AdRequest.Builder().build();
        mInterstitialAd_Arcade.loadAd(adRequest);


分离时

 @Override
public void onDetach(){
    super.onDetach();
    showIntAd();
} 


显示广告的方法

private void showIntAd(){
            int interstitial_counter = 
            mSharedPreferences.getInt(getString(R.string.pref_arcade_interstitial_counter), 0);
            if (interstitial_counter >= 15){
                if (mInterstitialAd_Arcade.isLoaded()) {
                    mInterstitialAd_Arcade.show();
                }
                    mInterstitialAd_Arcade.setAdListener(new AdListener(){
                    @Override
                    public void onAdOpened(){
                        Log.i(TAG, "Ad opened");
                    }

                    @Override
                    public void onAdFailedToLoad(int errorCode){
                        Log.e(TAG,  "Ad Failed to load: " + errorCode);
                    }
                    @Override
                    public void onAdClosed(){
                        Log.i(TAG, "Ad closed");
                        mEditor.putInt(getString(R.string.pref_arcade_interstitial_counter), 0);
                        mEditor.apply();
                    }
                });
            }
        }

1 个答案:

答案 0 :(得分:0)

问题是sharedPreference没有任何值(空)。 试试这个方法

private void showIntAd(){
            int interstitial_counter = 
            mSharedPreferences.getInt(getString(R.string.pref_arcade_interstitial_counter), 0);
            if (interstitial_counter ==null) {
                   if (mInterstitialAd_Arcade.isLoaded()) {
                    mInterstitialAd_Arcade.show();
                }
              }  
            if (interstitial_counter >= 15){
                if (mInterstitialAd_Arcade.isLoaded()) {
                    mInterstitialAd_Arcade.show();
                }

                //move the listener inside oncreate .
            }
        }