Android穿山甲SDK接入,已封装直接使用

杨和蔼
2023-12-01
已经历过适配过程中踩过的坑。直接使用方法即可调用广告显示

如插屏广告使用:loadExpressAd(TTAdManagerHolder.intersCodeId,300, 300)

信息流广告请看其它篇,直接使用即可

//是否显示广告
public static boolean showGG = false;


private boolean mIsExpress = false; //是否请求模板广告
private boolean mIsLoaded = false; //视频是否加载完成
private TTRewardVideoAd mttRewardVideoAd;

// 是否开放进阶奖励功能
private boolean isEnableAdvancedReward = false;
private RewardAdvancedInfo mRewardAdvancedInfo;

/**激励视频*/
public void loadAd(final String codeId, int orientation) {
    if(!showGG){
        return;
    }
    //step4:创建广告请求参数AdSlot,具体参数含义参考文档
    if(mTTAdNative==null){
        mTTAdNative = TTAdManagerHolder.get().createAdNative(activity);

    }
    AdSlot adSlot;
    if (mIsExpress) {
        //个性化模板广告需要传入期望广告view的宽、高,单位dp,

        adSlot = new AdSlot.Builder()
                .setCodeId(codeId)
                //此次加载广告的用途是实时加载,当用来作为缓存时,请使用:TTAdLoadType.LOAD
                .setAdLoadType(TTAdLoadType.LOAD)
                //模板广告需要设置期望个性化模板广告的大小,单位dp,激励视频场景,只要设置的值大于0即可
                .setExpressViewAcceptedSize(500,500)
                .build();
    } else {
        //模板广告需要设置期望个性化模板广告的大小,单位dp,代码位是否属于个性化模板广告,请在穿山甲平台查看

        adSlot = new AdSlot.Builder()
                //此次加载广告的用途是实时加载,当用来作为缓存时,请使用:TTAdLoadType.LOAD
                .setAdLoadType(TTAdLoadType.LOAD)
                .setCodeId(codeId)
                .build();
    }
    //step5:请求广告

    mTTAdNative.loadRewardVideoAd(adSlot, new TTAdNative.RewardVideoAdListener() {
        @Override
        public void onError(int code, String message) {
            Log.e(TAG, "Callback --> onError: " + code + ", " + String.valueOf(message));
            //TToast.show(activity, message);
        }

        //视频广告加载后,视频资源缓存到本地的回调,在此回调后,播放本地视频,流畅不阻塞。
        @Override
        public void onRewardVideoCached() {
            Log.e(TAG, "Callback --> onRewardVideoCached");
            mIsLoaded = true;
            TToast.show(activity, "Callback --> rewardVideoAd video cached");
        }

        @Override

        public void onRewardVideoCached(TTRewardVideoAd ad) {
            Log.e(TAG, "Callback --> onRewardVideoCached");
            mIsLoaded = true;
            TToast.show(activity, "Callback --> rewardVideoAd video cached");
            // ad.showRewardVideoAd(activity, TTAdConstant.RitScenes.CUSTOMIZE_SCENES, "scenes_test");

        }

        //视频广告的素材加载完毕,比如视频url等,在此回调后,可以播放在线视频,网络不好可能出现加载缓冲,影响体验。
        @Override

        public void onRewardVideoAdLoad(TTRewardVideoAd ad) {

            Log.e(TAG, "Callback --> onRewardVideoAdLoad");


            TToast.show(activity, "rewardVideoAd loaded 广告类型:" + getAdType(ad.getRewardVideoAdType()));
            mIsLoaded = false;
            mttRewardVideoAd = ad;
            mRewardAdvancedInfo = new RewardAdvancedInfo();
            mttRewardVideoAd.showRewardVideoAd(activity, TTAdConstant.RitScenes.CUSTOMIZE_SCENES, "scenes_test");
            mttRewardVideoAd.setRewardAdInteractionListener(new TTRewardVideoAd.RewardAdInteractionListener() {
                /*@Override
                public void onRewardArrived(boolean b, int i, Bundle bundle) {

                }*/

                @Override

                public void onAdShow() {
                    Log.d(TAG, "Callback --> rewardVideoAd show");
                    TToast.show(activity, "rewardVideoAd show");
                }

                @Override

                public void onAdVideoBarClick() {
                    Log.d(TAG, "Callback --> rewardVideoAd bar click");
                    TToast.show(activity, "rewardVideoAd bar click");
                }

                @Override

                public void onAdClose() {
                    Log.d(TAG, "Callback --> rewardVideoAd close");
                    TToast.show(activity, "rewardVideoAd close");
                    if (isEnableAdvancedReward && mRewardAdvancedInfo != null) {
                        Log.d(TAG, "本次奖励共发放:" + mRewardAdvancedInfo.getRewardAdvancedAmount());
                    }
                }

                //视频播放完成回调
                @Override
                public void onVideoComplete() {
                    Log.d(TAG, "Callback --> rewardVideoAd complete");
                    TToast.show(activity, "rewardVideoAd complete");
                }

                @Override
                public void onVideoError() {
                    Log.e(TAG, "Callback --> rewardVideoAd error");
                    TToast.show(activity, "rewardVideoAd error");
                }

                //视频播放完成后,奖励验证回调,rewardVerify:是否有效,rewardAmount:奖励梳理,rewardName:奖励名称
                @Override

                public void onRewardVerify(boolean rewardVerify, int rewardAmount, String rewardName, int errorCode, String errorMsg) {
                    String logString = "verify:" + rewardVerify + " amount:" + rewardAmount +
                            " name:" + rewardName + " errorCode:" + errorCode + " errorMsg:" + errorMsg;
                    Log.e(TAG, "Callback --> " + logString);
                    TToast.show(activity, logString);
                }

               /* @Override
                public void onRewardArrived(boolean isRewardValid, int rewardType, Bundle extraInfo) {
                    RewardBundleModel rewardBundleModel = new RewardBundleModel(extraInfo);
                    Log.e(TAG, "Callback --> rewardVideoAd has onRewardArrived " +
                            "\n奖励是否有效:" + isRewardValid +
                            "\n奖励类型:" + rewardType +
                            "\n奖励名称:" + rewardBundleModel.getRewardName() +
                            "\n奖励数量:" + rewardBundleModel.getRewardAmount() +
                            "\n建议奖励百分比:" + rewardBundleModel.getRewardPropose());
                    if (!isRewardValid) {
                        Log.d(TAG, "发送奖励失败 code:" + rewardBundleModel.getServerErrorCode() +
                                "\n msg:" + rewardBundleModel.getServerErrorMsg());
                        return;
                    }

                    if (!isEnableAdvancedReward) {
                        // 未使用进阶奖励功能
                        if (rewardType == TTRewardVideoAd.REWARD_TYPE_DEFAULT) {
                            Log.d(TAG, "普通奖励发放,name:" + rewardBundleModel.getRewardName() +
                                    "\namount:" + rewardBundleModel.getRewardAmount());
                        }
                    } else {
                        // 使用了进阶奖励功能
                        if (mRewardAdvancedInfo != null) {
                            mRewardAdvancedInfo.proxyRewardModel(rewardBundleModel, false);
                        }
                    }
                }*/

                @Override
                public void onSkippedVideo() {
                    Log.e(TAG, "Callback --> rewardVideoAd has onSkippedVideo");
                    TToast.show(activity, "rewardVideoAd has onSkippedVideo");
                }
            });

            mttRewardVideoAd.setRewardPlayAgainInteractionListener(new TTRewardVideoAd.RewardAdInteractionListener() {
                /*@Override
                public void onRewardArrived(boolean b, int i, Bundle bundle) {

                }*/

                @Override

                public void onAdShow() {
                    Log.d(TAG, "Callback --> rewardPlayAgain show");
                    TToast.show(activity, "rewardVideoAd show");
                }

                @Override

                public void onAdVideoBarClick() {
                    Log.d(TAG, "Callback --> rewardPlayAgain bar click");
                    TToast.show(activity, "rewardVideoAd bar click");
                }

                @Override

                public void onAdClose() {
                    Log.d(TAG, "Callback --> rewardPlayAgain close");
                    TToast.show(activity, "rewardVideoAd close");
                }

                //视频播放完成回调
                @Override
                public void onVideoComplete() {
                    Log.d(TAG, "Callback --> rewardPlayAgain complete");
                    TToast.show(activity, "rewardVideoAd complete");
                }

                @Override
                public void onVideoError() {
                    Log.e(TAG, "Callback --> rewardPlayAgain error");
                    TToast.show(activity, "rewardVideoAd error");
                }

                //视频播放完成后,奖励验证回调,rewardVerify:是否有效,rewardAmount:奖励梳理,rewardName:奖励名称
                @Override

                public void onRewardVerify(boolean rewardVerify, int rewardAmount, String rewardName, int errorCode, String errorMsg) {
                    String logString = "rewardPlayAgain verify:" + rewardVerify + " amount:" + rewardAmount +
                            " name:" + rewardName + " errorCode:" + errorCode + " errorMsg:" + errorMsg;
                    Log.e(TAG, "Callback --> " + logString);
                    TToast.show(activity, logString);
                }

               /* @Override
                public void onRewardArrived(boolean isRewardValid, int rewardType, Bundle extraInfo) {
                    RewardBundleModel rewardBundleModel = new RewardBundleModel(extraInfo);
                    Log.e(TAG, "Callback --> rewardPlayAgain has onRewardArrived " +
                            "\n奖励是否有效:" + isRewardValid +
                            "\n奖励类型:" + rewardType +
                            "\n奖励名称:" + rewardBundleModel.getRewardName() +
                            "\n奖励数量:" + rewardBundleModel.getRewardAmount() +
                            "\n建议奖励百分比:" + rewardBundleModel.getRewardPropose());

                    if (!isEnableAdvancedReward) {
                        // 再看一个未使用进阶奖励功能
                        if (rewardType == TTRewardVideoAd.REWARD_TYPE_DEFAULT) {
                            Log.d(TAG, "再看一个普通奖励发放,name:" + rewardBundleModel.getRewardName() +
                                    "\namount:" + rewardBundleModel.getRewardAmount());
                        }
                    } else {
                        // 再看一个使用了进阶奖励功能
                        if (mRewardAdvancedInfo != null) {
                            mRewardAdvancedInfo.proxyRewardModel(rewardBundleModel, true);
                        }
                    }
                }*/

                @Override
                public void onSkippedVideo() {
                    Log.e(TAG, "Callback --> rewardPlayAgain has onSkippedVideo");
                    TToast.show(activity, "rewardVideoAd has onSkippedVideo");
                }
            });
            mttRewardVideoAd.setDownloadListener(new TTAppDownloadListener() {
                @Override
                public void onIdle() {
                    mHasShowDownloadActive = false;
                }

                @Override
                public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
                    Log.d("DML", "onDownloadActive==totalBytes=" + totalBytes + ",currBytes=" + currBytes + ",fileName=" + fileName + ",appName=" + appName);

                    if (!mHasShowDownloadActive) {
                        mHasShowDownloadActive = true;
                        TToast.show(activity, "下载中,点击下载区域暂停", Toast.LENGTH_LONG);
                    }
                }

                @Override
                public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
                    Log.d("DML", "onDownloadPaused===totalBytes=" + totalBytes + ",currBytes=" + currBytes + ",fileName=" + fileName + ",appName=" + appName);
                    TToast.show(activity, "下载暂停,点击下载区域继续", Toast.LENGTH_LONG);
                }

                @Override
                public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
                    Log.d("DML", "onDownloadFailed==totalBytes=" + totalBytes + ",currBytes=" + currBytes + ",fileName=" + fileName + ",appName=" + appName);
                    TToast.show(activity, "下载失败,点击下载区域重新下载", Toast.LENGTH_LONG);
                }

                @Override
                public void onDownloadFinished(long totalBytes, String fileName, String appName) {
                    Log.d("DML", "onDownloadFinished==totalBytes=" + totalBytes + ",fileName=" + fileName + ",appName=" + appName);
                    TToast.show(activity, "下载完成,点击下载区域重新下载", Toast.LENGTH_LONG);
                }

                @Override
                public void onInstalled(String fileName, String appName) {
                    Log.d("DML", "onInstalled==" + ",fileName=" + fileName + ",appName=" + appName);
                    TToast.show(activity, "安装完成,点击下载区域打开", Toast.LENGTH_LONG);
                }
            });
        }
    });
}
private String getAdType(int type) {
    switch (type) {

        case TTAdConstant.AD_TYPE_COMMON_VIDEO:
            return "普通激励视频,type=" + type;

        case TTAdConstant.AD_TYPE_PLAYABLE_VIDEO:
            return "Playable激励视频,type=" + type;

        case TTAdConstant.AD_TYPE_PLAYABLE:
            return "纯Playable,type=" + type;

        case TTAdConstant.AD_TYPE_LIVE:
            return "直播流,type=" + type;
    }

    return "未知类型+type=" + type;
}

/**插屏广告*/
public void loadExpressAd(String codeId, int expressViewWidth, int expressViewHeight) {
    if(!showGG){
        return;
    }
    //step4:创建广告请求参数AdSlot,具体参数含义参考文档
    if(mTTAdNative==null){
        mTTAdNative = TTAdManagerHolder.get().createAdNative(activity);
    }
    AdSlot adSlot = new AdSlot.Builder()
            .setCodeId(codeId) //广告位id
            .setAdCount(1) //请求广告数量为1到3条
            .setExpressViewAcceptedSize(expressViewWidth, expressViewHeight) //期望模板广告view的size,单位dp
            .build();
    //step5:请求广告,对请求回调的广告作渲染处理

    mTTAdNative.loadInteractionExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
        @Override
        public void onError(int code, String message) {
            TToast.show(activity, "load error : " + code + ", " + message);
        }

        @Override

        public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
            if (ads == null || ads.size() == 0) {
                return;
            }
            LogUtils.v("success=="+ads.size());
            mTTAd = ads.get(0);
            bindAdListener(mTTAd);
            mTTAd.render();
            //TToast.show(activity, "load success !");
        }
    });
}
private void bindAdListener(final TTNativeExpressAd ad) {

    ad.setExpressInteractionListener(new TTNativeExpressAd.AdInteractionListener() {
        @Override

        public void onAdDismiss() {
           // TToast.show(activity, "广告关闭");
        }

        @Override

        public void onAdClicked(View view, int type) {
           // TToast.show(activity, "广告被点击");
        }

        @Override

        public void onAdShow(View view, int type) {
            TToast.show(activity, "广告展示");
        }

        @Override
        public void onRenderFail(View view, String msg, int code) {

            TToast.show(activity, msg + " code:" + code);
        }

        @Override
        public void onRenderSuccess(View view, float width, float height) {

            //返回view的宽高 单位 dp
            TToast.show(activity, "渲染成功");
            ad.showInteractionExpressAd(activity);

        }
    });
    bindDislike(ad, false);

    if (ad.getInteractionType() != TTAdConstant.INTERACTION_TYPE_DOWNLOAD) {
        return;
    }
    ad.setDownloadListener(new TTAppDownloadListener() {
        @Override
        public void onIdle() {
            TToast.show(activity, "点击开始下载", Toast.LENGTH_LONG);
        }

        @Override
        public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
            if (!mHasShowDownloadActive) {
                mHasShowDownloadActive = true;
                TToast.show(activity, "下载中,点击暂停", Toast.LENGTH_LONG);
            }
        }

        @Override
        public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
            TToast.show(activity, "下载暂停,点击继续", Toast.LENGTH_LONG);
        }

        @Override
        public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
            TToast.show(activity, "下载失败,点击重新下载", Toast.LENGTH_LONG);
        }

        @Override
        public void onInstalled(String fileName, String appName) {
            TToast.show(activity, "安装完成,点击图片打开", Toast.LENGTH_LONG);
        }

        @Override
        public void onDownloadFinished(long totalBytes, String fileName, String appName) {
            TToast.show(activity, "点击安装", Toast.LENGTH_LONG);
        }
    });
}
private void bindDislike(TTNativeExpressAd ad, boolean customStyle) {
    if (customStyle) {
        //使用自定义样式
        DislikeInfo dislikeInfo = ad.getDislikeInfo();
        if (dislikeInfo == null || dislikeInfo.getFilterWords() == null || dislikeInfo.getFilterWords().isEmpty()) {
            return;
        }
        final DislikeDialog dislikeDialog = new DislikeDialog(activity, dislikeInfo);
        dislikeDialog.setOnDislikeItemClick(new DislikeDialog.OnDislikeItemClick() {
            @Override
            public void onItemClick(FilterWord filterWord) {
                //屏蔽广告
                TToast.show(activity, "点击 " + filterWord.getName());
            }
        });
        dislikeDialog.setOnPersonalizationPromptClick(new DislikeDialog.OnPersonalizationPromptClick() {
            @Override
            public void onClick(PersonalizationPrompt personalizationPrompt) {
                TToast.show(activity, "点击了为什么看到此广告");
            }
        });
        ad.setDislikeDialog(dislikeDialog);
        return;
    }
    //使用默认模板中默认dislike弹出样式

    ad.setDislikeCallback(activity, new TTAdDislike.DislikeInteractionCallback() {
        @Override
        public void onShow() {

        }

        @Override
        public void onSelected(int position, String value, boolean enforce) {
            //TToast.show(mContext, "反馈了 " + value);
            TToast.show(activity, "\t\t\t\t\t\t\t感谢您的反馈!\t\t\t\t\t\t\n我们将为您带来更优质的广告体验", 3);
            if (enforce) {
                TToast.show(activity, "InteractionExpressActivity 模版插屏,穿山甲sdk强制将view关闭了 ");
            }
        }

        @Override
        public void onCancel() {
            TToast.show(activity, "点击取消 ");
        }

    });
}
public void loadNativeExpressAd(ListView mListView, ProjectsAdapter myAdapter, List<ProjectsItem> mData,
                                int w, int h){
    if(!showGG){
        return;
    }
    LIST_ITEM_COUNT = mData.size();
    int AdCount = LIST_ITEM_COUNT/10+1;
    if(AdCount>3){
        AdCount = 3;
    }
    //feed广告请求类型参数
    if(mTTAdNative==null){
        mTTAdNative = TTAdManagerHolder.get().createAdNative(activity);
    }
    AdSlot adSlot = new AdSlot.Builder()
            .setCodeId(TTAdManagerHolder.FeedCodeId) //广告位id
            .setSupportDeepLink(true)
            .setAdCount(AdCount) //请求广告数量为1到3条
            .setExpressViewAcceptedSize(w-30,0) //期望模板广告view的size,单位dp
            // .setAdLoadType(TTAdLoadType.PRELOAD)//推荐使用,用于标注此次的广告请求用途为预加载(当做缓存)还是实时加载,方便后续为开发者优化相关策略
            .build();
    mTTAdNative.loadNativeExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
        //广告请求失败
        @Override
        public void onError(int code, String message) {
            LogUtils.v(code+"loadFeedAd=="+message);
        }
        //广告请求成功
        @Override
        public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
            LogUtils.v("onNativeExpressAdLoad=="+ads.size());
            if (ads == null || ads.isEmpty()) {
                TToast.show(activity, "on FeedAdLoaded: ad is null!");
                return;
            }

            for (TTNativeExpressAd ad : ads) {
                int random = (int) (Math.random() * LIST_ITEM_COUNT);
                LogUtils.v("========"+random);
                try{

                    ProjectsItem bean = new ProjectsItem();

                    bean.setNativeExpressAd(ad);
                    bindAdListener1(ad);
                    mData.add(random, bean);

                }catch (Exception e){

                }

            }


            myAdapter.notifyDataSetChanged();
        }
    });

}
public void loadNativeExpressAd(ListView mListView, NativeAdapter myAdapter, List<BannerBean> mData,
                                int w, int h){
    if(!showGG){
        return;
    }
    LIST_ITEM_COUNT = mData.size();
    int AdCount = LIST_ITEM_COUNT/10+1;
    //feed广告请求类型参数
    if(mTTAdNative==null){
        mTTAdNative = TTAdManagerHolder.get().createAdNative(activity);
    }

    AdSlot adSlot = new AdSlot.Builder()
            .setCodeId(TTAdManagerHolder.FeedCodeId) //广告位id
            .setSupportDeepLink(true)
            .setAdCount(AdCount) //请求广告数量为1到3条
            .setExpressViewAcceptedSize(w-30,0) //期望模板广告view的size,单位dp
           // .setAdLoadType(TTAdLoadType.PRELOAD)//推荐使用,用于标注此次的广告请求用途为预加载(当做缓存)还是实时加载,方便后续为开发者优化相关策略
            .build();
    mTTAdNative.loadNativeExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
        //广告请求失败
        @Override
        public void onError(int code, String message) {
            LogUtils.v(code+"loadFeedAd=="+message);
        }
        //广告请求成功
        @Override
        public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
            LogUtils.v("onNativeExpressAdLoad=="+ads.size());
            if (ads == null || ads.isEmpty()) {
                TToast.show(activity, "on FeedAdLoaded: ad is null!");
                return;
            }

            for (TTNativeExpressAd ad : ads) {
                int random = (int) (Math.random() * LIST_ITEM_COUNT);
                LogUtils.v("========"+random);
                try{

                    BannerBean bean = new BannerBean();

                    bean.setNativeExpressAd(ad);
                    bindAdListener1(ad);
                    mData.add(random, bean);

                }catch (Exception e){

                }

            }


            myAdapter.notifyDataSetChanged();
        }
    });

}
private void bindAdListener1(final TTNativeExpressAd adTmp) {
    adTmp.setExpressInteractionListener(new TTNativeExpressAd.ExpressAdInteractionListener() {
        @Override

        public void onAdClicked(View view, int type) {
            TToast.show(activity, "广告被点击");
        }

        @Override

        public void onAdShow(View view, int type) {
            TToast.show(activity, "广告展示");
        }

        @Override
        public void onRenderFail(View view, String msg, int code) {
            TToast.show(activity, msg + " code:" + code);
        }

        @Override
        public void onRenderSuccess(View view, float width, float height) {
            //返回view的宽高 单位 dp
            TToast.show(activity, "渲染成功");
        }
    });
    adTmp.render();

}
/**
 * 信息流
 * 加载feed广告
 */
private static  int LIST_ITEM_COUNT = 0;
public void loadListAd(RecyclerView mListView, ClassifyListAdapter myAdapter, List<BannerBean> mData,
                       int w,int h) {
    if(!showGG){
        return;
    }
    LIST_ITEM_COUNT = mData.size();
    int AdCount = LIST_ITEM_COUNT/10+1;
    //feed广告请求类型参数
    if(mTTAdNative==null){
        mTTAdNative = TTAdManagerHolder.get().createAdNative(activity);
    }
    LogUtils.v(w,h);



    AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(TTAdManagerHolder.FeedCodeId)
            .setImageAcceptedSize(w, h)
            .setAdCount(AdCount)
            .build();
    //调用feed广告异步请求接口

    mTTAdNative.loadFeedAd(adSlot, new TTAdNative.FeedAdListener() {
        @Override
        public void onError(int code, String message) {

            LogUtils.v(code+"loadFeedAd=="+message);
            TToast.show(activity, message);
        }

        @Override

        public void onFeedAdLoad(List<TTFeedAd> ads) {

            if (ads == null || ads.isEmpty()) {
                TToast.show(activity, "on FeedAdLoaded: ad is null!");
                return;
            }

            for (int i = 0; i < LIST_ITEM_COUNT; i++) {
                mData.add(null);
            }

            int count = mData.size();

            for (TTFeedAd ad : ads) {


                int random = (int) (Math.random() * LIST_ITEM_COUNT);
                LogUtils.v("========"+random);
                try{
                    LogUtils.v(ad.getClass().getName());
                    BannerBean bean = new BannerBean();

                    bean.setFeedAd(ad);
                    mData.add(random, bean);

                }catch (Exception e){

                }

            }


            myAdapter.notifyDataSetChanged();
        }
    });
}

/**banner广告展示*/
private TTAdNative mTTAdNative;
private TTNativeExpressAd mTTAd;
public void loadExpressAd(FrameLayout mExpressContainer,String codeId, float expressViewWidth, float expressViewHeight){
    if(!showGG){
        mExpressContainer.setVisibility(View.GONE);
        return;
    }
    if(mTTAdNative==null){
        mTTAdNative = TTAdManagerHolder.get().createAdNative(activity);
        TTAdManagerHolder.get().requestPermissionIfNecessary(activity);
    }
    AdSlot adSlot = new AdSlot.Builder()
            .setCodeId(codeId) //广告位id
            .setAdCount(3) //请求广告数量为1到3条
            .setExpressViewAcceptedSize(expressViewWidth, expressViewHeight) //期望模板广告view的size,单位dp
            .build();
    //step5:请求广告,对请求回调的广告作渲染处理

    mTTAdNative.loadBannerExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
        @Override
        public void onError(int code, String message) {
            LogUtils.v(code+"loadBannerExpressAd="+message);
            mExpressContainer.removeAllViews();
        }

        @Override

        public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
            LogUtils.v("onNativeExpressAdLoad="+ads.size());
            if (ads == null || ads.size() == 0) {
                return;
            }
            mTTAd = ads.get(0);
            mTTAd.setSlideIntervalTime(30 * 1000);
            bindAdListener(mTTAd,mExpressContainer);

             TToast.show(activity,"load success!");
            mTTAd.render();
        }
    });

}
private boolean mHasShowDownloadActive = false;
public void bindAdListener(TTNativeExpressAd ad, FrameLayout mExpressContainer) {

    ad.setExpressInteractionListener(new TTNativeExpressAd.ExpressAdInteractionListener() {
        @Override

        public void onAdClicked(View view, int type) {
            TToast.show(activity, "广告被点击");
        }

        @Override

        public void onAdShow(View view, int type) {
            TToast.show(activity, "广告展示");
        }

        @Override
        public void onRenderFail(View view, String msg, int code) {
            //Log.e("ExpressView", "render fail:" + (System.currentTimeMillis() - startTime));
            TToast.show(activity, 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(activity, "渲染成功");
            mExpressContainer.removeAllViews();
            mExpressContainer.addView(view);
        }
    });
    //dislike设置
    bindDislike(ad,  mExpressContainer,false);

    if (ad.getInteractionType() != TTAdConstant.INTERACTION_TYPE_DOWNLOAD) {
        return;
    }
    ad.setDownloadListener(new TTAppDownloadListener() {
        @Override
        public void onIdle() {
            TToast.show(activity, "开始下载", Toast.LENGTH_LONG);
        }

        @Override
        public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
            if (!mHasShowDownloadActive) {
                mHasShowDownloadActive = true;
                TToast.show(activity, "下载中,点击暂停", Toast.LENGTH_LONG);
            }
        }

        @Override
        public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
            TToast.show(activity, "下载暂停,点击继续", Toast.LENGTH_LONG);
        }

        @Override
        public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
            TToast.show(activity, "下载失败,点击重新下载", Toast.LENGTH_LONG);
        }

        @Override
        public void onInstalled(String fileName, String appName) {
            TToast.show(activity, "安装完成,点击图片打开", Toast.LENGTH_LONG);
        }

        @Override
        public void onDownloadFinished(long totalBytes, String fileName, String appName) {
            TToast.show(activity, "点击安装", Toast.LENGTH_LONG);
        }
    });
}
/**
 * 设置广告的不喜欢, 注意:强烈建议设置该逻辑,如果不设置dislike处理逻辑,则模板广告中的 dislike区域不响应dislike事件。
 *
 * @param ad
 * @param customStyle 是否自定义样式,true:样式自定义
 */

private void bindDislike(TTNativeExpressAd ad,FrameLayout mExpressContainer, boolean customStyle) {
    if (customStyle) {
        //使用自定义样式
        final DislikeInfo dislikeInfo = ad.getDislikeInfo();
        if (dislikeInfo == null || dislikeInfo.getFilterWords() == null || dislikeInfo.getFilterWords().isEmpty()) {
            return;
        }
        final DislikeDialog dislikeDialog = new DislikeDialog(activity, dislikeInfo);
        dislikeDialog.setOnDislikeItemClick(new DislikeDialog.OnDislikeItemClick() {
            @Override
            public void onItemClick(FilterWord filterWord) {
                //屏蔽广告
                TToast.show(activity, "点击 " + filterWord.getName());
                //用户选择不喜欢原因后,移除广告展示
                mExpressContainer.removeAllViews();
            }
        });
        dislikeDialog.setOnPersonalizationPromptClick(new DislikeDialog.OnPersonalizationPromptClick() {
            @Override
            public void onClick(PersonalizationPrompt personalizationPrompt) {
                TToast.show(activity, "点击了为什么看到此广告");
            }
        });
        ad.setDislikeDialog(dislikeDialog);
        return;
    }
    //使用默认模板中默认dislike弹出样式

    ad.setDislikeCallback(activity, new TTAdDislike.DislikeInteractionCallback() {
        @Override
        public void onShow() {

        }

        @Override
        public void onSelected(int position, String value, boolean enforce) {
            TToast.show(activity, "点击 " + value);
            mExpressContainer.removeAllViews();
            //用户选择不喜欢原因后,移除广告展示
            if (enforce) {
                TToast.show(activity, "模版Banner 穿山甲sdk强制将view关闭了");
            }
        }

        @Override
        public void onCancel() {
            TToast.show(activity, "点击取消 ");
        }

    });
}
 类似资料: