大家可以先参考我的上一篇博客 插屏广告 传送门
首先创建一个脚本具体内容如下
package com.unity3d.player.chuanshanjia;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdDislike;
import com.bytedance.sdk.openadsdk.TTAdLoadType;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.unity3d.player.tools.ChuanShanJiaUtil;
import com.unity3d.player.tools.ShowSeqUtils;
import com.unity3d.player.tools.TToast;
import java.util.List;
public class Stream{
@SuppressLint("StaticFieldLeak")
private static Stream _Instance;
public static Stream Inst(){
if(_Instance == null){
_Instance = new Stream();
}
return _Instance;
}
private final String TAG = "Stream";
private TTAdNative mTTAdNative;
private FrameLayout mExpressContainer;
private Context mContext;
private TTNativeExpressAd mTTAd;
private final ShowSeqUtils ssu = new ShowSeqUtils();
public void Init(Context context,FrameLayout frameLayout,String[] codeIds) {
mContext = context;
mExpressContainer = frameLayout;
//step2:创建TTAdNative对象,createAdNative(Context context) banner广告context需要传入Activity对象
mTTAdNative = TTAdManagerHolder.get().createAdNative(mContext);
//step3:(可选,强烈建议在合适的时机调用):申请部分权限,如read_phone_state,防止获取不了imei时候,下载类广告没有填充的问题。
TTAdManagerHolder.get().requestPermissionIfNecessary(mContext);
int adload_seq = ssu.loadShowSeq();
loadExpressAd(codeIds, adload_seq,codeIds[0],0);
}
private void loadExpressAd(final String[] codeIds, final int adload_seq, final String prime_rit, final int cur){
try {
mExpressContainer.removeAllViews();
}catch (Exception e){
Log.d(TAG, "loadExpressAd: Exception:"+e.toString());
}
float expressViewWidth = ChuanShanJiaUtil.getScreenWidthDp(mContext);
float expressViewHeight = ChuanShanJiaUtil.getHeight((Activity) mContext);
//step4:创建广告请求参数AdSlot,具体参数含义参考文档
Log.d(TAG, "Stream loadExpressAd 2");
AdSlot adSlot = new AdSlot.Builder()
.setCodeId(codeIds[cur]) //广告位id
.setSupportDeepLink(true)
.setAdCount(1) //请求广告数量为1到3条
.setExpressViewAcceptedSize(expressViewWidth,expressViewHeight) //期望模板广告view的size,单位dp
.setAdLoadType(TTAdLoadType.LOAD)
.setAdloadSeq(adload_seq)
.setPrimeRit(prime_rit)
.build();
Log.d(TAG, "Stream loadExpressAd 3");
//step5:请求广告,对请求回调的广告作渲染处理
mTTAdNative.loadNativeExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
@Override
public void onError(int code, String message) {
TToast.show(mContext, "load error : " + code + ", " + message);
try {
mExpressContainer.removeAllViews();
}catch (Exception e){
Log.d(TAG, "loadExpressAd: Exception:"+e.toString());
}
if(cur<2){
loadExpressAd(codeIds,adload_seq,prime_rit,cur+1);
}
if(cur==2){
//最后一次也失败更新字段结束
ssu.writeToFile(adload_seq+1);
}
}
@Override
public void onNativeExpressAdLoad(List ads) {
if (ads == null || ads.size() == 0){
if(cur<2){
loadExpressAd(codeIds,adload_seq,prime_rit,cur+1);
}else{
//最后一次也为空更新字段结束
ssu.writeToFile(adload_seq+1);
return;
}
}
assert ads != null;
mTTAd = ads.get(0);
bindAdListener(mTTAd);
startTime = System.currentTimeMillis();
ssu.writeToFile(adload_seq+1);
mTTAd.render();
}
});
}
private long startTime = 0;
private boolean mHasShowDownloadActive = false;
private void bindAdListener(TTNativeExpressAd ad) {
ad.setExpressInteractionListener(new TTNativeExpressAd.ExpressAdInteractionListener() {
@Override
public void onAdClicked(View view, int type) {
TToast.show(mContext, "广告被点击");
}
@Override
public void onAdShow(View view, int type) {
TToast.show(mContext, "广告展示");
}
@Override
public void onRenderFail(View view, String msg, int code) {
Log.e("ExpressView","render fail:"+(System.currentTimeMillis() - startTime));
TToast.show(mContext, msg+" code:"+code);
}
@Override
public void onRenderSuccess(View view, float width, float height) {
Log.e("ExpressView","render suc:"+(System.currentTimeMillis() - startTime));
//返回view的宽高 单位 dp
TToast.show(mContext, "渲染成功");
mExpressContainer.removeAllViews();
mExpressContainer.addView(view);
}
});
//dislike设置
bindDislike(ad);
if (ad.getInteractionType() != TTAdConstant.INTERACTION_TYPE_DOWNLOAD){
return;
}
ad.setDownloadListener(new TTAppDownloadListener() {
@Override
public void onIdle() {
TToast.show(mContext, "点击开始下载", Toast.LENGTH_LONG);
}
@Override
public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
if (!mHasShowDownloadActive) {
mHasShowDownloadActive = true;
TToast.show(mContext, "下载中,点击暂停", Toast.LENGTH_LONG);
}
}
@Override
public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
TToast.show(mContext, "下载暂停,点击继续", Toast.LENGTH_LONG);
}
@Override
public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
TToast.show(mContext, "下载失败,点击重新下载", Toast.LENGTH_LONG);
}
@Override
public void onInstalled(String fileName, String appName) {
TToast.show(mContext, "安装完成,点击图片打开", Toast.LENGTH_LONG);
}
@Override
public void onDownloadFinished(long totalBytes, String fileName, String appName) {
TToast.show(mContext, "点击安装", Toast.LENGTH_LONG);
}
});
}
/**
* 设置广告的不喜欢,注意:强烈建议设置该逻辑,如果不设置dislike处理逻辑,则模板广告中的 dislike区域不响应dislike事件。
* @param ad
*
*/
private void bindDislike(TTNativeExpressAd ad) {
//使用默认模板中默认dislike弹出样式
ad.setDislikeCallback((Activity) mContext, new TTAdDislike.DislikeInteractionCallback() {
@Override
public void onShow() {
TToast.show(mContext, "bindDislike onShow");
}
@Override
public void onSelected(int position, String value, boolean enforce) {
TToast.show(mContext, "点击 " + value);
//用户选择不喜欢原因后,移除广告展示
mExpressContainer.removeAllViews();
if (enforce) {
TToast.show(mContext, "NativeWaterfallActivity 模版信息流 sdk强制移除View ");
}
}
@Override
public void onCancel() {
TToast.show(mContext, "点击取消 ");
}
});
}
}
首先在主Activity里面写入如下代码
private View[] views;
private int[] sdkIds;
private int viewIndex = 0;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
sdkIds = new int[]{R.layout.activity_banner,R.layout.activity_native_waterfall};
views = new View[sdkIds.length];
for (int sdkId : sdkIds) {
addView(sdkId);
}
}
@SuppressLint("InflateParams")
public void addView(int id){
LayoutInflater inflater = LayoutInflater.from(this);
// 第一个参数就是要加载的布局id,
// 第二个参数是指给该布局的外部再嵌套一层父布局,如果不需要就直接传null。
View view = inflater.inflate(id, null);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,FrameLayout.LayoutParams.WRAP_CONTENT);
params.topMargin = 0;
params.gravity = Gravity.TOP|Gravity.CENTER_HORIZONTAL;
this.addContentView(view,params);
// lts.add(id,view);
views[viewIndex] = view;
viewIndex +=1;
}
public void Destoryview(int id){
this.runOnUiThread(new Runnable() {
@Override
public void run() {
if(id==-1) {
for (View view : views) {
//设置为不可见
view.setVisibility(View.INVISIBLE);
}
}
else{
if(views[id]!=null){
//设置为不可见
views[id].setVisibility(View.INVISIBLE);
}
else {
Log.d("Unity", "lts.get(id) == null");
}
}
}
});
}
@Override protected void onDestroy ()
{
super.onDestroy();
Destoryview(-1);
}
在res\layout文件夹里面创建两个xml文件 具体内容如下
activity_banner
activity_native_waterfall
使用方式
public void Stream(String codeId)
{
Log.d(TAG, "CallStream: "+codeId);
FrameLayout mExpressStreamContainer = findViewById(R.id.express_container);
String[] codeIds = {codeId};
Log.d(TAG, "CallStream: "+codeIds[0]);
Stream.Inst().Init(this,mExpressStreamContainer,codeIds);
}
下一篇 Banner广告 传送门