我想在用户关闭/离开特定片段时投放插页式广告。为此,我运行了一种方法,在showIntAd()
中显示onDetach()
测试广告可以正常显示Log.i(TAG, "Ad closed");
运行正常,但是如果我尝试putInt
或getInt
之后的所有代码将无法执行。
基本上我想将一个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();
}
});
}
}
最佳答案
问题是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 .
}
}