一、导入谷歌广告SDK流程(官方文档)
1.项目级build.gradle中加入google()
,如下:
allprojects {
repositories {
google()
}
}
2.应用级build.gradle,在dependencies中引入implementation 'com.google.android.gms:play-services-ads:19.6.0'
,如下:
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'com.google.android.gms:play-services-ads:19.6.0'
}
3.修改AndroidManifest.xml文件
将在AdMob中注册的应用ID(可在 AdMob 界面中找到)以<meta-data>方式添加到AndroidManifest.xml中,如下:
<manifest>
<application>
<!-- Sample AdMob app ID: ca-app-pub-3940256099942544~3347511713 -->
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy"/>
</application>
</manifest>
!!!注:在实际应用中,需要将上述value对应的值替换为实际AdMob应用ID,若只是demo中,可以使用上述sample的应用ID。
4.初始化SDK
在application中调用如下方法初始化SDK
MobileAds.initialize(context, new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
Log.e(TAG, "AdMob init rst:" + JSON.toJson(initializationStatus.getAdapterStatusMap()));
}
});
二、谷歌广告实现
先上效果图,如下:
效果图
1.在xml布局中广告显示位置添加占位view,如下
<FrameLayout
android:id="@+id/fl_adplaceholder"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/dp_15" />
2.自定义广告显示样式,使用UnifiedNativeAdView类对应一个原生广告,用于展示该广告素材资源的视图(例如,展示屏幕截图素材资源的 ImageView),均应是UnifiedNativeAdView对象的子对象。ad_unified_img_body.xml布局如下:
<com.google.android.gms.ads.formats.UnifiedNativeAdView
android:id="@+id/native_ad_view"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:minHeight="@dimen/dp_73">
<RelativeLayout
android:layout_width="@dimen/dp_130"
android:layout_height="@dimen/dp_73">
<com.google.android.gms.ads.formats.MediaView
android:id="@+id/ad_media"
android:layout_width="@dimen/dp_130"
android:layout_height="@dimen/dp_73"
android:layout_gravity="center_horizontal" />
<TextView
android:id="@+id/ad_choices"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="@dimen/dp_12"
android:textColor="#707070"
android:background="@drawable/ad_mob_icon_bg"
android:layout_marginTop="@dimen/dp_5"
android:layout_marginEnd="@dimen/dp_5"
android:layout_alignParentEnd="true"
android:paddingStart="@dimen/dp_4"
android:paddingEnd="@dimen/dp_4"
android:text="@string/ad_google"/>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="@dimen/dp_16"
android:gravity="center_vertical"
android:orientation="vertical">
<TextView
android:id="@+id/ad_headline"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#262D44"
android:layout_marginTop="@dimen/dp_3"
android:ellipsize="end"
android:singleLine="true"
android:text=""
android:textSize="@dimen/dp_15"
android:textStyle="bold" />
<TextView
android:id="@+id/ad_body"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="2"
android:textColor="#818799"
android:ellipsize="end"
android:textSize="@dimen/dp_13" />
</LinearLayout>
</LinearLayout>
</com.google.android.gms.ads.formats.UnifiedNativeAdView>
3.开始加载广告内容
/**
* 加载广告
* @param context cont
* @param id 广告id
* @param listener 监听
*/
public static void loadAd(Context context, String id, OnAdLoadListener listener) {
if (!checkThread()) {
return;
}
Log.e(TAG, "AdMob load ad " + id);
AdLoader.Builder builder = new AdLoader.Builder(context, id);
builder.forUnifiedNativeAd(new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {
@Override
public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {
//广告数据加载成功
if (listener != null) {
listener.onAdLoaded(unifiedNativeAd);
}
}
});
builder.withAdListener(new AdListener() {
@Override
public void onAdFailedToLoad(LoadAdError loadAdError) {
String error =
String.format("domain: %s, code: %d, message: %s, cause: %s", loadAdError.getDomain(),
loadAdError.getCode(), loadAdError.getMessage(), loadAdError.getCause());
Log.e(AdMob.TAG, error);
if (listener != null) {
listener.onAdFailedToLoad(loadAdError);
}
}
});
//设置广告的属性
VideoOptions videoOptions = new VideoOptions.Builder().setStartMuted(true).build();
NativeAdOptions adOptions = new NativeAdOptions.Builder().setVideoOptions(videoOptions)
//.setAdChoicesPlacement(ADCHOICES_BOTTOM_RIGHT)//设置广告中自带的广告标识view的位置,不设置默认显示在右上角
.build();
builder.withNativeAdOptions(adOptions);
AdLoader adLoader = builder.build();
adLoader.loadAd(new AdRequest.Builder().build());
}
4.广告数据加载成功后,使用UnifiedNativeAd对象填充自定义的广告视图view
AdMob.loadAd(getActivity(), "ca-app-pub-3940256099942544/2247696110",
new AdMob.OnAdLoadListener() {
@Override
public void onAdLoaded(UnifiedNativeAd unifiedNativeAd) {
if (getActivity() == null
|| getActivity().isFinishing()
|| getActivity().isDestroyed()) {
unifiedNativeAd.destroy();
return;
}
FrameLayout frameLayout = (FrameLayout) getActivity().getLayoutInflater()
.inflate(R.layout.ad_unified_img_body, null);
View view = frameLayout.findViewById(R.id.view_bg);
UnifiedNativeAdView adView =
(UnifiedNativeAdView) frameLayout.findViewById(R.id.native_ad_view);
AdMob.populateUnifiedNativeAdViewForImgAndBody(unifiedNativeAd, adView);
float aspectRatio = unifiedNativeAd.getMediaContent().getAspectRatio();
FrameLayout.LayoutParams layoutParams =
(FrameLayout.LayoutParams) adView.getLayoutParams();
if (layoutParams == null) {
layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
layoutParams.height = ad.getResources().getDimensionPixelSize(R.dimen.dp_73);
view.setVisibility(View.VISIBLE);
ad.removeAllViews();
ad.addView(frameLayout, layoutParams);
}
@Override
public void onAdFailedToLoad(LoadAdError loadAdError) {
}
});
上述填充数据populateUnifiedNativeAdViewForImgAndBody()方法如下:
public static void populateUnifiedNativeAdViewForImgAndBody(UnifiedNativeAd nativeAd,
UnifiedNativeAdView adView) {
// Set the media view.
adView.setHeadlineView(adView.findViewById(R.id.ad_headline));
adView.setMediaView(adView.findViewById(R.id.ad_media));
adView.setBodyView(adView.findViewById(R.id.ad_body));
// The mediaContent are guaranteed to be in every UnifiedNativeAd.
adView.getMediaView().setMediaContent(nativeAd.getMediaContent());
adView.getMediaView().setImageScaleType(ImageView.ScaleType.CENTER_INSIDE);
((TextView) adView.getHeadlineView()).setText(nativeAd.getHeadline());
// These assets aren't guaranteed to be in every UnifiedNativeAd, so it's important to
// check before trying to display them.
if (nativeAd.getBody() == null) {
adView.getBodyView().setVisibility(View.INVISIBLE);
} else {
adView.getBodyView().setVisibility(View.VISIBLE);
((TextView) adView.getBodyView()).setText(nativeAd.getBody());
}
// This method tells the Google Mobile Ads SDK that you have finished populating your
// native ad view with this native ad.
adView.setNativeAd(nativeAd);
// Get the video controller for the ad. One will always be provided, even if the ad doesn't
// have a video asset.
VideoController vc = nativeAd.getVideoController();
// Updates the UI to say whether or not this ad has a video asset.
if (vc.hasVideoContent()) {
Log.e(TAG,
String.format(Locale.getDefault(), "Video status: Ad contains a %.2f:1 video asset.",
vc.getAspectRatio()));
// Create a new VideoLifecycleCallbacks object and pass it to the VideoController. The
// VideoController will call methods on this object when events occur in the video
// lifecycle.
vc.setVideoLifecycleCallbacks(new VideoController.VideoLifecycleCallbacks() {
@Override
public void onVideoEnd() {
// Publishers should allow native ads to complete video playback before
// refreshing or replacing them with another ad in the same UI location.
Log.e(TAG, "Video status: Video playback has ended.");
super.onVideoEnd();
}
});
} else {
Log.e(TAG, "Video status: Ad does not contain a video asset.");
}
}
网友评论