要实现Admob视频奖励只播放一次的功能,可以使用SharedPreferences来记录视频奖励的播放状态。以下是一个示例代码,演示了如何使用SharedPreferences来记录和检查视频奖励的播放状态:
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.ads.AdError;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdRequest.Builder;
import com.google.android.gms.ads.FullScreenContentCallback;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.OnUserEarnedRewardListener;
import com.google.android.gms.ads.rewarded.RewardItem;
import com.google.android.gms.ads.rewarded.RewardedAd;
import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback;
public class MainActivity extends AppCompatActivity {
private RewardedAd rewardedAd;
private SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化AdMob
MobileAds.initialize(this, initializationStatus -> {});
// 创建SharedPreferences实例,用于记录视频奖励的播放状态
sharedPreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
// 检查是否已经播放过视频奖励
boolean isRewardPlayed = sharedPreferences.getBoolean("isRewardPlayed", false);
if (!isRewardPlayed) {
loadRewardedAd();
} else {
Toast.makeText(this, "视频奖励已播放过", Toast.LENGTH_SHORT).show();
}
}
// 加载视频奖励广告
private void loadRewardedAd() {
Builder adRequestBuilder = new AdRequest.Builder();
AdRequest adRequest = adRequestBuilder.build();
RewardedAd.load(this, "YOUR_REWARDED_AD_UNIT_ID", adRequest, new RewardedAdLoadCallback() {
@Override
public void onAdLoaded(RewardedAd ad) {
rewardedAd = ad;
showRewardedAd();
}
@Override
public void onAdFailedToLoad(LoadAdError error) {
Toast.makeText(MainActivity.this, "加载视频奖励广告失败", Toast.LENGTH_SHORT).show();
}
});
}
// 播放视频奖励广告
private void showRewardedAd() {
if (rewardedAd != null) {
rewardedAd.setFullScreenContentCallback(new FullScreenContentCallback() {
@Override
public void onAdShowedFullScreenContent() {
// 广告显示时,将播放状态标记为已播放
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("isRewardPlayed", true);
editor.apply();
}
@Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
Toast.makeText(MainActivity.this, "播放视频奖励广告失败", Toast.LENGTH_SHORT).show();
}
@Override
public void onAdDismissedFullScreenContent() {
rewardedAd = null;
}
});
rewardedAd.show(this, new OnUserEarnedRewardListener() {
@Override
public void onUserEarnedReward(RewardItem rewardItem) {
// 用户完成了观看广告的要求,可以给予奖励
Toast.makeText(MainActivity.this, "获得奖励: " + rewardItem.getAmount() + " " + rewardItem.getType(), Toast.LENGTH_SHORT).show();
}
});
}
}
}
请注意,上述代码中的 "YOUR_REWARDED_AD_UNIT_ID" 需要替换为您自己的广告单元ID。此外,还需要在AndroidManifest.xml文件中添加适当的AdMob应用ID和权限声明。
上一篇:Admob视频奖励广告每天的限制
下一篇:AdMob实施