
第一步:引入依赖包
//admob广告
implementation ‘com.google.android.gms:play-services-ads:17.2.0’
第二步:在清单文件中设置appID
android:name=”com.google.android.gms.ads.APPLICATION_ID”
android:value=”ca-app-pub-xxxxxxxxxxxxxxxxxxxx”/>
第三步:在布局文件中设置广告显示的具体位置
android:id=”@+id/adView”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignParentBottom=”true”
android:layout_centerHorizontal=”true”
ads:adSize=”SMART_BANNER”
>
第四步:初始化Admob
// 初始化Admob 这个地方填appid 注意
MobileAds.initialize(this, “ca-app-pub-xxxxxxxxxxxxxxxxxxxx”);
第五步: 在对应的Activity或Fragment中设置广告显示
private static final String AD_UNIT_ID = “ca-app-pub-xxxxxxxxxxxxxxxxxxxx”;
private void initAdmob() {
mAdView = findViewById(R.id.adView);
mAdView.setAdUnitId(AD_UNIT_ID);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
mAdView.setAdListener(new AdListener() {
@Override
public void onAdLoaded() {
// Code to be executed when an ad finishes loading.
//广告加载完成后,系统会执行 onAdLoaded() 方法。
// 如果您想延迟向 Activity 或 Fragment 中添加AdView的操作(例如,延迟到您确定广告会加载时),可以在此处进行。
}
@Override
public void onAdFailedToLoad(int errorCode) {
// Code to be executed when an ad request fails.
//onAdFailedToLoad() 是唯一包含参数的方法。errorCode 参数会指明发生了何种类型的失败。系统将这些可能的类型值定义为AdRequest类中的如下常量:
//ERROR_CODE_INTERNAL_ERROR – 内部出现问题;例如,收到广告服务器的无效响应。
//ERROR_CODE_INVALID_REQUEST – 广告请求无效;例如,广告单元 ID 不正确。
//ERROR_CODE_NETWORK_ERROR – 由于网络连接问题,广告请求失败。
//ERROR_CODE_NO_FILL – 广告请求成功,但由于缺少广告资源,未返回广告。
}
@Override
public void onAdOpened() {
// Code to be executed when an ad opens an overlay that
// covers the screen.
//此方法会在用户点按广告时调用。
}
@Override
public void onAdClicked() {
// Code to be executed when the user clicks on an ad.
}
@Override
public void onAdLeftApplication() {
// Code to be executed when the user has left the app.
//此方法会于 onAdOpened() 之后在用户点击打开其他应用(例如,Google Play)时调用,从而在后台运行当前应用。
}
@Override
public void onAdClosed() {
// Code to be executed when the user is about to return
// to the app after tapping on an ad.
//在用户查看广告的目标网址后返回应用时,会调用此方法。应用可以使用此方法恢复暂停的活动,或执行任何其他必要的操作,以做好互动准备。
// 有关 Android API Demo 应用中广告监听器方法的实现方式,请参阅 AdMob AdListener 示例。
}
});
}
相关推荐: 阿里2023财年Q4营收2082亿元 调整后净利润同比增长38%阿里2023财年Q4营收2082亿元 调整后净利润同比增长38%
5月18日消息,阿里巴巴发布2023财年第四财季及全年财报。财报显示,2023财年第四季度阿里巴巴营收2082亿元,同比增长2%;净利润219.96亿元,去年同期净亏损为183.57亿元;非公认会计准则(Non-GAAP),净利润273.75亿元,同比增长38…
码刀科技(www.lekshop.cn)是国内知名企业级电商平台提供商,为企业级商家提供最佳的电商平台搭建(多种模式电商平台搭建:B2B/B2B2C/B2C/O2O/新零售/跨境等)、平台管理系统开发及互联网采购解决方案服务, 联系客服了解更多.