dependencies {
implementation 'com.google.android.gms:play-services-ads:19.7.0'
}
2.在AdMob模板的MainActivity中,添加以下代码来显示广告:
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
// 声明一个全局的InterstitialAd变量
private InterstitialAd mInterstitialAd;
// 在onCreate方法中初始化InterstitialAd
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(getString(R.string.admob_interstitial_ad_unit_id));
mInterstitialAd.loadAd(new AdRequest.Builder().build());
// 创建方法来显示InterstitialAd
private void showInterstitial() {
if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("TAG", "The interstitial wasn't loaded yet.");
}
}
// 在合适的位置调用showInterstitial方法来显示广告
3.在AdMob模板的activity_main.xml中添加以下代码来显示横幅广告:
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.AdRequest;
// 在onCreate方法中,获取AdView并加载广告
AdView adView = findViewById(R.id.adView);
adView.loadAd(new AdRequest.Builder().build());