Skip to content

Instantly share code, notes, and snippets.

@zhangzhibin
Last active July 27, 2021 02:06
Show Gist options
  • Save zhangzhibin/e8e60e68de3c23f3e8c7937876061c64 to your computer and use it in GitHub Desktop.
Save zhangzhibin/e8e60e68de3c23f3e8c7937876061c64 to your computer and use it in GitHub Desktop.
laya + ironsource android sdk helper, contact me at https://xmanyou.com
module SdkHelper{
export class IronSourceHelper{
public static ironsource:Laya.IPlatformClass;
public static init(){
if(!this.ironsource){
this.ironsource = Laya.PlatformClass.createClass("sdkhelper.IronSourceHelper");
}
let js1 = `window["IronSourceHelper"].onInterstitialReadyChange(%s)`;
let js2 = `window["IronSourceHelper"].onVideoReadyChange(%s)`;
this.ironsource.call("setReadyStateListener", js1, js2);
}
public static checkState(){
if(!this.ironsource) {
return;
}
this.ironsource.call("checkAdState");
}
public static loadInterstitial(){
if(!this.ironsource) {
return;
}
this.ironsource.call("loadInterstitial");
}
public static isInterstitialReadyAsync(callback){
// return new Promise((r,j)=>{
// if(!this.ironsource) {
// r(false);
// }
// this.ironsource.callWithBack((ready)=> {
// console.info("isInterstitialReady: " + ready);
// r(ready);
// }, "isInterstitialReady"
// );
// });
if(!this.ironsource) {
callback(false);
return false;
}
this.ironsource.callWithBack((ready)=> {
console.info("isInterstitialReady: " + ready);
// r(ready);
callback(ready);
}, "isInterstitialReady"
);
}
public static isInterstitialReady() {
return this._interstitialReady;
}
public static showInterstitialAsync(callback){
// return new Promise((r,j)=>{
// if(!this.ironsource) {
// r();
// }
//
// IronSourceHelper._interstitialCloseCallback = r;
// let js = `window["IronSourceHelper"].onInterstitialClosed()`;
// this.ironsource.call("showInterstitial", js);
// });
if(!this.ironsource) {
callback(false);
return;
}
this._interstitialReady = false;
this._interstitialCloseCallback = callback;
let js = `window["IronSourceHelper"].onInterstitialClosed()`;
this.ironsource.call("showInterstitial", js);
}
private static _interstitialCloseCallback;
public static onInterstitialClosed(){
console.info("===> Interstitial Closed");
if(this._interstitialCloseCallback){
this._interstitialCloseCallback();
}
this._interstitialCloseCallback = null;
}
public static isVideoReady(){
return this._videoReady;
}
public static isVideoReadyAsync(callback){
if(!this.ironsource) {
callback(false);
return false;
}
this.ironsource.callWithBack((ready)=> {
console.info("isRewardedVideoReady: " + ready);
// r(ready);
callback(ready);
}, "isRewardedVideoReady"
);
// return new Promise((r,j)=>{
// if(!this.ironsource) {
// r(false);
// }
// this.ironsource.callWithBack((ready)=> {
// console.info("isInterstitialReady: " + ready);
// r(ready);
// }, "isRewardedVideoReady"
// );
// });
}
public static showVideoAdsAsync(callback){
// return new Promise((r,j)=>{
// if(!this.ironsource) {
// r(false);
// }
// let jsClosed = `window["IronSourceHelper"].onVideoClosed(%s);`;
// IronSourceHelper._videoClosedCallback = r;
// this.ironsource.call("showRewardedVideo", jsClosed);
// });
if(!this.ironsource) {
callback(false);
return;
}
this._videoReady = false;
let jsClosed = `window["IronSourceHelper"].onVideoClosed(%s);`;
this._videoClosedCallback = callback;
this.ironsource.call("showRewardedVideo", jsClosed);
}
private static _videoClosedCallback;
public static onVideoClosed(result:boolean){
console.info("===> Video Closed");
if(this._videoClosedCallback){
this._videoClosedCallback(result);
}
this._videoClosedCallback = null;
}
private static _interstitialReady = false;
private static _videoReady = false;
public static onInterstitialReadyChange(ready:boolean){
this._interstitialReady = ready;
console.info("onInterstitialReadyChange: " +ready);
}
public static onVideoReadyChange(ready:boolean){
this._videoReady = ready;
console.info("onVideoReadyChange: " +ready);
}
}
window["IronSourceHelper"] = IronSourceHelper;
}
package sdkhelper;
import android.app.Activity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import com.ironsource.mediationsdk.ISBannerSize;
import com.ironsource.mediationsdk.IronSource;
import com.ironsource.mediationsdk.IronSourceBannerLayout;
import com.ironsource.mediationsdk.integration.IntegrationHelper;
import com.ironsource.mediationsdk.logger.IronSourceError;
import com.ironsource.mediationsdk.model.Placement;
import com.ironsource.mediationsdk.sdk.BannerListener;
import com.ironsource.mediationsdk.sdk.InterstitialListener;
import com.ironsource.mediationsdk.sdk.RewardedVideoListener;
import demo.MainActivity;
import layaair.game.browser.ConchJNI;
import layaair.game.browser.ExportJavaFunction;
import vip.minigame.laya.demo.R;
//import org.cocos2dx.lib.Cocos2dxActivity;
//import org.cocos2dx.lib.Cocos2dxJavascriptJavaBridge;
public class IronSourceHelper {
private static final String TAG = "IronSourceHelper";
public static final String IRONSOUCE_APP_KEY = "<app key>";
private static Activity _app = null;
private static IronSourceBannerLayout _banner = null;
private static FrameLayout _bannerContainer = null;
public static void initIronSource(Activity activity){
_app = activity;
// IronSource 激励广告事件
IronSource.setRewardedVideoListener(new RewardedVideoListener() {
/**
* Invoked when the RewardedVideo ad view has opened.
* Your Activity will lose focus. Please avoid performing heavy
* tasks till the video ad will be closed.
*/
@Override
public void onRewardedVideoAdOpened() {
Log.d(TAG, "onRewardedVideoAdOpened: ");
}
/*Invoked when the RewardedVideo ad view is about to be closed.
Your activity will now regain its focus.*/
@Override
public void onRewardedVideoAdClosed() {
Log.d(TAG, "onRewardedVideoAdClosed: ");
IronSourceHelper.onRewardedClosed();
}
/**
* Invoked when there is a change in the ad availability status.
*
* @param - available - value will change to true when rewarded videos are *available.
* You can then show the video by calling showRewardedVideo().
* Value will change to false when no videos are available.
*/
@Override
public void onRewardedVideoAvailabilityChanged(boolean available) {
//Change the in-app 'Traffic Driver' state according to availability.
Log.d(TAG, String.format("onRewardedVideoAvailabilityChanged: %b", available));
_notifyRewardedStateChange();
// if(_interstitialReadyListener.length()>0){
// final String readyScript = String.format(_rewardedReadyListener, IronSource.isRewardedVideoAvailable()?"true":"false");
// ConchJNI.RunJS(readyScript);
// }
}
/**
/**
* Invoked when the user completed the video and should be rewarded.
* If using server-to-server callbacks you may ignore this events and wait *for the callback from the ironSource server.
*
* @param - placement - the Placement the user completed a video from.
*/
@Override
public void onRewardedVideoAdRewarded(Placement placement) {
/** here you can reward the user according to the given amount.
String rewardName = placement.getRewardName();
int rewardAmount = placement.getRewardAmount();
*/
Log.d(TAG, String.format("onRewardedVideoAdRewarded: %s", placement.getPlacementName()));
IronSourceHelper.onRewardedSuccess();;
}
/* Invoked when RewardedVideo call to show a rewarded video has failed
* IronSourceError contains the reason for the failure.
*/
@Override
public void onRewardedVideoAdShowFailed(IronSourceError error) {
Log.d(TAG, String.format("onRewardedVideoAdShowFailed: [%d] %s", error.getErrorCode(), error.getErrorMessage()));
IronSourceHelper.onRewardedFailed();
}
/*Invoked when the end user clicked on the RewardedVideo ad
*/
@Override
public void onRewardedVideoAdClicked(Placement placement){
Log.d(TAG, String.format("onRewardedVideoAdClicked: %s", placement.getPlacementName()));
}
/*
Note: the events AdStarted and AdEnded below are not available for all supported rewarded video
ad networks. Check which events are available per ad network you choose
to include in your build.
We recommend only using events which register to ALL ad networks you
include in your build.
* Invoked when the video ad starts playing.
*/
@Override
public void onRewardedVideoAdStarted(){
Log.d(TAG, "onRewardedVideoAdStarted: ");
}
/* Invoked when the video ad finishes plating. */
@Override
public void onRewardedVideoAdEnded(){
Log.d(TAG, "onRewardedVideoAdEnded: ");
}
});
// IronSource 插页广告事件
IronSource.setInterstitialListener(new InterstitialListener() {
/**
Invoked when Interstitial Ad is ready to be shown after load function was called.
*/
@Override
public void onInterstitialAdReady() {
Log.d(TAG, "onInterstitialAdReady: ");
_notifyInterstitialStateChange();
// _interstitialReady = true;
}
/**
invoked when there is no Interstitial Ad available after calling load function.
*/
@Override
public void onInterstitialAdLoadFailed(IronSourceError error) {
Log.d(TAG, String.format("onInterstitialAdLoadFailed: [%d] %s", error.getErrorCode(), error.getErrorMessage()));
}
/**
Invoked when the Interstitial Ad Unit is opened
*/
@Override
public void onInterstitialAdOpened() {
Log.d(TAG, "onInterstitialAdOpened: ");
}
/*
* Invoked when the ad is closed and the user is about to return to the application.
*/
@Override
public void onInterstitialAdClosed() {
Log.d(TAG, "onInterstitialAdClosed: ");
IronSourceHelper.onInterstitialClosed();
}
/*
* Invoked when the ad was opened and shown successfully.
*/
@Override
public void onInterstitialAdShowSucceeded() {
Log.d(TAG, "onInterstitialAdShowSucceeded: ");
}
/**
* Invoked when Interstitial ad failed to show.
// @param error - An object which represents the reason of showInterstitial failure.
*/
@Override
public void onInterstitialAdShowFailed(IronSourceError error) {
Log.d(TAG, String.format("onInterstitialAdShowFailed: [%d] %s", error.getErrorCode(), error.getErrorMessage()));
}
/*
* Invoked when the end user clicked on the interstitial ad.
*/
@Override
public void onInterstitialAdClicked() {
Log.d(TAG, "onInterstitialAdClicked: ");
}
});
// 初始化IronSource
// https://developers.ironsrc.com/ironsource-mobile/android/android-sdk/#step-5
IronSource.init(activity, IRONSOUCE_APP_KEY);
// IronSource.init(activity, IronSourceHelper.IRONSOUCE_APP_KEY, IronSource.AD_UNIT.BANNER);
// IronSource.init(activity, IronSourceHelper.IRONSOUCE_APP_KEY, IronSource.AD_UNIT.INTERSTITIAL);
// IronSource.init(activity, IronSourceHelper.IRONSOUCE_APP_KEY, IronSource.AD_UNIT.REWARDED_VIDEO);
//// // 初始化Banner
// initBanner();
// 检查接入是否成功
Log.d("IronSourceHelper", "=====> Validate IronSource");
IntegrationHelper.validateIntegration(activity);
IronSource.setAdaptersDebug(true);
// // 启动后自动加载banner
// showBanner();
}
public static boolean isRewardedVideoReady(){
boolean ready = IronSource.isRewardedVideoAvailable();
ExportJavaFunction.CallBackToJS(IronSourceHelper.class,"isRewardedVideoReady",ready);
return ready;
}
public static void showRewardedVideo(String closeScript){
// _onRewardedSuccessScript = successScript;
// _onRewardedFailScript = failScript;
Log.d(TAG, "showRewardedVideo: " + closeScript);
_onRewardedClosedScript = closeScript;
IronSource.showRewardedVideo();
}
public static void onRewardedClosed(){
if(_onRewardedClosedScript.length()>0){
final String resultScript = String.format(IronSourceHelper._onRewardedClosedScript, _rewardedSuccess?"true":"false");
ConchJNI.RunJS(resultScript);
// _app.runOnGLThread(new Runnable() {
// @Override
// public void run() {
// Log.d(TAG, "onRewardedClosed: => " + resultScript);
//// Cocos2dxJavascriptJavaBridge.evalString(resultScript);
// }
// });
}
_onRewardedClosedScript = "";
}
// private static String _onRewardedSuccessScript = "";
// private static String _onRewardedFailScript = "";
private static String _onRewardedClosedScript = "";
private static boolean _rewardedSuccess = false;
public static void onRewardedSuccess(){
_rewardedSuccess = true;
// if(_onRewardedSuccessScript.length()>0){
// _app.runOnGLThread(new Runnable() {
// @Override
// public void run() {
// Cocos2dxJavascriptJavaBridge.evalString(_onRewardedSuccessScript);
// }
// });
// }
// _onRewardedSuccessScript = "";
// _onRewardedFailScript = "";
}
public static void onRewardedFailed(){
_rewardedSuccess = false;
// if(_onRewardedFailScript.length()>0){
// _app.runOnGLThread(new Runnable() {
// @Override
// public void run() {
// Cocos2dxJavascriptJavaBridge.evalString(_onRewardedFailScript);
// }
// });
// }
// _onRewardedSuccessScript = "";
// _onRewardedFailScript = "";
}
public static boolean isInterstitialReady(){
// return IronSource.isInterstitialReady();
// DEBUG
// return false;
boolean ready = IronSource.isInterstitialReady();
ExportJavaFunction.CallBackToJS(IronSourceHelper.class,"isInterstitialReady",ready);
return ready;
}
private static void _notifyInterstitialStateChange(){
if(_interstitialReadyListener!=null && _interstitialReadyListener.length()>0){
final String readyScript = String.format(_interstitialReadyListener, IronSource.isInterstitialReady()?"true":"false");
ConchJNI.RunJS(readyScript);
}
}
private static void _notifyRewardedStateChange(){
if(_rewardedReadyListener!=null && _rewardedReadyListener.length()>0){
final String readyScript = String.format(_rewardedReadyListener, IronSource.isRewardedVideoAvailable()?"true":"false");
ConchJNI.RunJS(readyScript);
}
}
public static void loadInterstitial(){
if(IronSource.isInterstitialReady()){
_notifyInterstitialStateChange();
return;
}else{
_notifyInterstitialStateChange();
}
IronSource.loadInterstitial();
}
private static String _interstitalCloseScript = "";
public static void showInterstitial(String script){
IronSource.showInterstitial();
_interstitalCloseScript = script;
}
public static void onInterstitialClosed(){
if(_interstitalCloseScript.length()>0){
// Cocos2dxJavascriptJavaBridge.evalString(_interstitalCloseScript);
final String script = _interstitalCloseScript;
ConchJNI.RunJS(script);
// _app.runOnGLThread(new Runnable() {
// @Override
// public void run() {
//// Cocos2dxJavascriptJavaBridge.evalString(script);
// }
// });
}
loadInterstitial();
}
private static String _interstitialReadyListener = "";
private static String _rewardedReadyListener = "";
public static void setReadyStateListener(String interstitialListener, String rewardedListener){
_interstitialReadyListener = interstitialListener;
_rewardedReadyListener = rewardedListener;
}
public static void checkAdState(){
_notifyInterstitialStateChange();
_notifyRewardedStateChange();
}
public static void initBanner(boolean showAfterLoad){
// _app = MainActivity
if(_app == null){
Log.w(TAG, "initBanner: App not inited");
return;
}
// 创建banner容器
FrameLayout bannerContainer = new FrameLayout(_app);
FrameLayout.LayoutParams containerParams = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT
);
containerParams.gravity = Gravity.BOTTOM;
_bannerContainer = bannerContainer;
// 创建banner view
IronSourceBannerLayout banner = IronSource.createBanner(_app, ISBannerSize.BANNER);
_banner = banner;
FrameLayout.LayoutParams bannerParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
bannerContainer.addView(banner, 0, bannerParams);
// 把bannerContainer添加到MainActivity里
_app.addContentView(bannerContainer, containerParams);
banner.setBannerListener(new BannerListener() {
@Override
public void onBannerAdLoaded() {
// Called after a banner ad has been successfully loaded
Log.d(TAG, "onBannerAdLoaded: ===> Banner loaded");
}
@Override
public void onBannerAdLoadFailed(IronSourceError error) {
Log.d(TAG, "onBannerAdLoadFailed: ===> Banner load failed: " + error.getErrorMessage());
// Called after a banner has attempted to load an ad but failed.
_app.runOnUiThread(new Runnable() {
@Override
public void run() {
_bannerContainer.removeAllViews();
// TODO: 也许可以尝试重新创建banner view并load
}
});
}
@Override
public void onBannerAdClicked() {
// Called after a banner has been clicked.
Log.d(TAG, "onBannerAdClicked: ===> Banner Clicked");
}
@Override
public void onBannerAdScreenPresented() {
// Called when a banner is about to present a full screen content.
Log.d(TAG, "onBannerAdScreenPresented: ===> Banner Showed");
}
@Override
public void onBannerAdScreenDismissed() {
// Called after a full screen content has been dismissed
Log.d(TAG, "onBannerAdScreenDismissed: ===> Banner Hided");
}
@Override
public void onBannerAdLeftApplication() {
// Called when a user would be taken out of the application context.
Log.d(TAG, "onBannerAdLeftApplication: ");
}
});
IronSource.loadBanner(_banner);
if(!showAfterLoad){
hideBanner();
}
}
public static void showBanner(){
if(_banner == null){
Log.w(TAG, "showBanner: Banner Not Inited");
return;
}
Log.d(TAG, "showBanner: ===> start loading banner");
_banner.setVisibility(View.VISIBLE);
}
public static void hideBanner(){
if(_banner == null){
Log.w(TAG, "hideBanner: Banner Not Inited");
return;
}
Log.d(TAG, "hideBanner: ===> hide banner");
_banner.setVisibility(View.INVISIBLE);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment