// 小程序启动后30秒内才能展示插屏广告
const AFTER_LAUNCH_TIME = 31000;
// 距离上次展示广告60秒后,才能展示插屏广告
const NEXT_SHOW_TIME = 61000;
// 是否可以展示广告
let canShow = false;
let timer = null;
// 是否为第一次展示广告
let isFirstShow = true;
// 休眠函数
function sleep(ms) {
if (timer) {
clearTimeout(timer);
}
return new Promise((resolve) => {
timer = setTimeout(() => {
resolve({});
}, ms);
});
}
class AdController {
/**
* @description: 控制广告是否展示
* @return {boolean}
*/
get canShow() {
return canShow;
}
/**
* @description: 判断广告是否第一次展示
* @return {boolean}
*/
get isFirstShow() {
return isFirstShow;
}
}
const controller = new AdController();
class InterstitialAdController {
constructor(adid) {
// 初始化 & 加载插屏广告
this.adid = adid;
this.ad = tt.createInterstitialAd({
adUnitId: this.adid,
});
this.ad.load();
}
/**
* @description: 在app的onLaunch方法中调用
* @return {Promise<void>}
*/
async onAppLaunch() {
// 检查是否可以展示广告,如果可以则设置定时器,否则直接返回
if (controller.canShow) {
await sleep(AFTER_LAUNCH_TIME);
this.ad.show(); // 显示广告
} else {
this.ad.hide(); // 隐藏广告
}
}
}
/**
* @description: 初始化一个插屏广告,开发者需要将参数置换为自己小程序的广告id
*/
function initAd(adId) {
// 如果canShow=false,则不能播放视频
if (!controller.canShow) return;
// 展示插屏广告
this.ad.show();
// 设置广告关闭的回调函数
this.ad.onClose(() => {
console.log('close');
// 休眠60s后把canShow置为true
this.afterNext();
tt.redirectTo({
url: '/pages/index/index',
});
});
canShow = false;
isFirstShow = false;
}
/**
* @description: 返回canShow的值
* @return {boolean}
*/
initAd.prototype.getCanShow = function() {
return controller.canShow;
};
/**
* @description: 返回isFirstShow的值
* @return {boolean}
*/
initAd.prototype.getIsFirstShow = function() {
return controller.isFirstShow;
};
// 导入 InterstitialAdController 类
import InterstitialAdController from './InterstitialAdController';
// 创建 InterstitialAdController 实例,传入广告的相关信息
export const interstitialAdController = new InterstitialAdController(`xxxxx`);