Freestar Ads Mediation React Native Android - freestarcapital/SDK_documentation_Android GitHub Wiki

Instructions for setting up React Native app for Android

Getting Started

Start displaying Freestar Ads in your existing React Native app running on Android by following the simple steps below.

Requirements

• Before we begin, you must have a working React Native app running on an Android device. This document will not show how to create a React Native app running under Android as that would be beyond the scope of Freestar Ads Mediation.

• Make sure you have the latest version of Android Studio.

Modify Android Project

Open the Android native build project using Android Studio. It is located in [your react project]/android folder.

Follow the Native Android Project Setup Guide here, which is modification of the build.gradle and AndroidManifest.xml

After making the changes to build.gradle and AndroidManifest.xml, return here. It should not take very long. Make sure you uncommented the following line in your app/build.gradle:

implementation 'com.freestar.android.ads:react-native-android:1.2.1'

Install our npm package

In your React Native project root folder, install our Freestar npm package:

npm install --save @freestar/freestar-plugin-react-native
(the latest npm package version is 1.3.6)

NOTE: if you already have the plugin installed, you should update it:

npm update --save @freestar/freestar-plugin-react-native

Modify MainActivity.java

In Android Studio, open MainActivity.java

In the onCreate method of MainActivity.java initialize Freestar. It should look something like this:

//Put these import statements at the top
import com.freestar.android.ads.AdRequest;
import com.freestar.android.ads.FreeStarAds;  
import android.os.Bundle;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Freestar begin

    /**
     * Note: When the enable-test-ads flag is set to [true], there will be a dialog prompt to choose 
     * mediation partners.  Set to [false] to remove that dialog and when getting ready to release
     * to production.
     * 
    */
    FreeStarAds.enableTestAds(true); //set false for production
    FreeStarAds.enableLogging(true); //set false for production
    AdRequest adRequest = new AdRequest(this);
    adRequest.addCustomTargeting("someParam1", "someValue1"); //optional targeting param for pre-fetched ads
    adRequest.addCustomTargeting("someParam2", "someValue2"); //optional targeting param for pre-fetched ads

    //Uncomment the following line if you wish to utilize App Open Ads in your Android app
    //FreeStarAds.requestAppOpenAds("app-open-ad-placement", true, null);   

    FreeStarAds.init(this, "XqjhRR", adRequest);  //Use our test key "XqjhRR" for all testing runs

    //The following init also works if you don't use custom targeting 
    //FreeStarAds.init(this, "XqjhRR");

    //Freestar end
  }

Modify MainApplication.java

In Android Studio, open MainApplication.java

Please add FreestarReactPackage: packages.add(new com.freestar.android.ads.react.FreestarReactPackage());

It may look something like the following:

  private final ReactNativeHost mReactNativeHost =
      new ReactNativeHost(this) {
        @Override
        public boolean getUseDeveloperSupport() {
          return BuildConfig.DEBUG;
        }

        @Override
        protected List getPackages() {
          @SuppressWarnings("UnnecessaryLocalVariable")
          List packages = new PackageList(this).getPackages();
          // Packages that cannot be autolinked yet can be added manually here, for example:
          // packages.add(new MyReactNativePackage());
            packages.add(new com.freestar.android.ads.react.FreestarReactPackage());
          return packages;
        }

        @Override
        protected String getJSMainModuleName() {
          return "index";
        }
      };

Network Security Config

Add network_security_config.xml to the [ProjectRoot]/android/app/src/main/res/xml folder (If folder does not exist, please create it).

Displaying Ads

The final piece to the puzzle is displaying ads in React Native js code.

In your application js, make sure to import our Freestar React plugin:

import FreestarReactBridge from '@freestar/freestar-plugin-react-native';
import BannerAd from '@freestar/freestar-plugin-react-native/BannerAd';
import MrecBannerAd from '@freestar/freestar-plugin-react-native/MrecBannerAd';
import SmallNativeAd from '@freestar/freestar-plugin-react-native/SmallNativeAd';
import MediumNativeAd from '@freestar/freestar-plugin-react-native/MediumNativeAd';

Fullscreen Interstitial Ads

We start by subscribing to the Interstitial callbacks:

FreestarReactBridge.subscribeToInterstitialCallbacks2((eventName, placement, eventMap) => {
       if(eventName === "onInterstitialLoaded") {

         if (placement == 'not defined') {  //Important: Check if the placement comes in as the literal 'not defined'
             placement = null;
         }

         Alert.alert('Interstitial: ' + eventMap.winningBidder);

         FreestarReactBridge.showInterstitialAd(placement);  //placement cannot be empty string '', but can be null or any string.

       } else if (eventName === "onInterstitialClicked") {

       } else if (eventName === "onInterstitialShown") {

       } else if (eventName === "onInterstitialFailed") {

           Alert.alert('Interstitial Ad not available');

       } else if (eventName === "onInterstitialDismissed") {

       } else {
          console.log("unknown event");
       }
     });

To load an interstitial ad:

Note: Please do not "prefetch" the next interstial ad on app startup or after dismissals or no-fills; we do this automatically and internally for you.

//In this case, we use the default placement, so we pass null for the placement name.
FreestarReactBridge.loadInterstitialAd(null);

Fullscreen Rewarded Ads

We start by subscribing to the Rewarded callbacks:

FreestarReactBridge.subscribeToRewardCallbacks2((eventName, placement, rewardName = '', rewardAmount = 0, eventMap) => {
     if (eventName === "onRewardedFailed") {

          Alert.alert('Reward Ad not available');

     } else if (eventName === "onRewardedDismissed") {

     } else if(eventName === "onRewardedLoaded") {

         Alert.alert('Rewarded: ' + eventMap.winningBidder);

         if (placement == 'not defined') {  //Important: Check if the placement comes in as the literal 'not defined'
             placement = null;  
         }
         //placement cannot be empty string '', but can be null or any string.
         FreestarReactBridge.showRewardAd(placement, "Coins", 50, "myuserId", "12345678");

     } else if (eventName === "onRewardedCompleted") {

         console.log("reward ad completed: awarded " + rewardAmount + ' ' + rewardName);

     } else if (eventName === "onRewardedShown") {

     } else if (eventName === "onRewardedShowFailed") {

          Alert.alert('Reward Ad was available but failed to show');

     } else {
        console.log("unknown event");
     }
   });

To load a Rewarded ad:

Note: Please do not "prefetch" the next rewarded ad on app startup or after dismissals or no-fills; we do this automatically and internally for you.

//In this case, we use the default placement, so we pass null for the placement name.
FreestarReactBridge.loadRewardAd(null);

Small Banner Ad 320x50

      <BannerAd
         style={{width: 320, height: 50}}    //Do not use other values besides 320 and 50 for small banner
         requestOptions={
            {
               size: 'BANNER',
               //placement: 'home_page_p1' //NOTE: if this placement has not been setup in the back-end, then do NOT specify placement
               targetingParams: {
                     'someparam1': 'somevalue1',
                     'someparam2': 'somevalue2',
                     'someparam3': 'somevalue3',
               },
               testDeviceIds: ['deviceId1','deviceId2', 'deviceId3']
            }
         }
         onBannerAdLoaded={someBannerLoadedHandler}
         onBannerAdFailedToLoad={someBannerFailedHandler}
      />
function someBannerLoadedHandler({ nativeEvent}) {
   console.log('loaded banner ad. placement: ' + nativeEvent.placement + ' winningBidder: ' + nativeEvent.winningBidder);
}

Medium Rectangle Banner Ad 300x250 - MREC

      <BannerAd
         style={{width: 300, height: 250}}    //Do not use other values besides 300 and 250 for mrec banner
         requestOptions={
            {  
               size: 'MREC',
               //placement: 'home_page_p1' //NOTE: if this placement has not been setup in the back-end, then do NOT specify placement
               targetingParams: {
                     'someparam1': 'somevalue1',
                     'someparam2': 'somevalue2',
                     'someparam3': 'somevalue3',
               },
               testDeviceIds: ['deviceId1','deviceId2', 'deviceId3']
            }
         }
         onBannerAdLoaded={someBannerLoadedHandler}
         onBannerAdFailedToLoad={someBannerFailedHandler}
      />

Another simple way to display MREC is as follows. Specify 'MrecBannerAd' and do not specify the 'size' in requestOptions.

      <MrecBannerAd
         style={{width: 300, height: 250}}    //Do not use other values besides 300 and 250 for mrec banner
         requestOptions={
            {
               //placement: 'home_page_p1' //NOTE: if this placement has not been setup in the back-end, then do NOT specify placement
               targetingParams: {
                     'someparam1': 'somevalue1',
                     'someparam2': 'somevalue2',
                     'someparam3': 'somevalue3',
               },
               testDeviceIds: ['deviceId1','deviceId2', 'deviceId3']
            }
         }
         onBannerAdLoaded={someBannerLoadedHandler}
         onBannerAdFailedToLoad={someBannerFailedHandler}
      />

Small Native Ad 360x100

      //Note: The ad width should actually be the full screen width.  360 (below) is for demonstration purposes.
      <SmallNativeAd
         style={{width: 360, height: 100}}
         requestOptions={
            {
               //placement: 'home_page_p1' //NOTE: if this placement has not been setup in the back-end, then do NOT specify placement
               targetingParams: {
                     'someparam1': 'somevalue1',
                     'someparam2': 'somevalue2',
                     'someparam3': 'somevalue3',
               },
               testDeviceIds: ['deviceId1','deviceId2', 'deviceId3']
            }
         }
         onNativeAdLoaded={someNativeLoadedHandler}
         onNativeAdFailedToLoad={someNativeFailedHandler}
      />
function someNativeLoadedHandler({ nativeEvent}) {
   console.log('loaded native ad. placement: ' + nativeEvent.placement + ' winningBidder: ' + nativeEvent.winningBidder);
}

Medium Native Ad 360x350

      //Note: The ad width should actually be the full screen width.  360 (below) is for demonstration purposes.
      <MediumNativeAd
         style={{width: 360, height: 350}}
         requestOptions={
            {
               //placement: 'home_page_p1' //NOTE: if this placement has not been setup in the back-end, then do NOT specify placement
               targetingParams: {
                     'someparam1': 'somevalue1',
                     'someparam2': 'somevalue2',
                     'someparam3': 'somevalue3',
               },
               testDeviceIds: ['deviceId1','deviceId2', 'deviceId3']
            }
         }
         onNativeAdLoaded={someNativeLoadedHandler}
         onNativeAdFailedToLoad={someNativeFailedHandler}
      />

For more information on how to optionally customize the look and feel of the SmallNativeAd or MediumNativeAd please see our Android Native Ad Unit document.

App Open Ad

App Open Ad is a fullscreen ad that shows when the app starts (including 'cold starts') and when the app is resumed from the background.

To utilize App Open Ads in your Android app, call the following method before FreeStarAds.init in MainActivity.java:

FreeStarAds.requestAppOpenAds("app-open-ad-placement", true, null);   //Obtain a proper placement from our Solutions Team
FreeStarAds.init(...);

Thumbnail Ad

Freestar supports Thumbnail Ads. These are small, floating box ads that overlay your application content. They are not part of your layout design, but you can choose their initial screen location when they first appear. Users can drag them around and can close them via an 'X' button, similar to YouTube 'mini-player' mode.

Load Thumbnail Ad:

    FreestarReactBridge.loadThumbnailAd(null);  //Optional placement or null for default placement

Display Thumbnail Ad:

Subscribe to the Thumbnail Ad callbacks:

FreestarReactBridge.subscribeToThumbnailAdCallbacks((eventName, placement, eventMap) => {

    if(eventName === "onThumbnailAdLoaded") {

      console.log("Thumbnail Ad: " + eventMap.winningBidder);

      if (placement == 'not defined')
         placement = null;

         /*
            'bottomLeft' or 'bottomRight' or 'topLeft' or 'topRight' are possible initial screen
             location values of the Thumbnail Ad or you can simply pass null (default bottomLeft).
             The last 2 parameters are the X and Y margin in DP.  In this sample, we just use 0 and 0.
         */
         FreestarReactBridge.showThumbnailAd(placement, 'bottomLeft', 0, 0);

    } else if (eventName === "onThumbnailAdClicked") {

      Alert.alert('Thumbnail Ad clicked');

    } else if (eventName === "onThumbnailAdShown") {

    } else if (eventName === "onThumbnailAdFailed") {

        Alert.alert('Thumbnail Ad not available');

    } else if (eventName === "onThumbnailAdDismissed") {

    } else {
       console.log("unknown event");
    }
});

PaidEvent

A PaidEvent occurs when an ad is shown on the screen. PaidEvent contains the following information:

adType The type of ad that got paid for, which is one of the following [interstitial | banner | rewardvideo | preroll | native | thumbnail]
adSize The size of the ad that got paid, which is one of the following [320x50 | 300x250 | 320x480 | 180x180 | 0x0 (native)]
placement The ad placement; can be `not defined` if it was not specified in the original ad request, which is fine.
nativeAdTemplate Applies only to native ads and is the size of the native ad template requested: [small | medium]
cpm Real-time CPM
winningPartner The partner who won the auction.
winningBidder If the winningPartner(above) supports server-to-server mediation, then this may be set to the highest bidder from that sub-auction.
userId The UserId set by `FreestarReactBridge.setUserId('my-test-user-id');` Here for convenience.
ifa If available on device, this is the IAB-specific Advertising ID
status Typically, the status will be `OK`, which means no problems occurred for this PaidEvent. _However_, there can be a status of `"NA"` (Not Available) - In some cases, the reported CPM (above) is not available from the winningPartner, therefore an estimated CPM was used.

Setup OnPaid listener:

FreestarReactBridge.setUserId('my-test-user-id');  //Optional

FreestarReactBridge.subscribeToOnPaidEvents((eventName, paidEvent) => {

   if(eventName === "onPaidEvent") {
     console.log(

               "PaidEvent{ " +
                   "adType='" + paidEvent.adType + '\'' +
                   ", adSize='" + paidEvent.adSize + '\'' +
                   ", placement='" + paidEvent.placement + '\'' +
                   ", nativeAdTemplate=" + paidEvent.nativeAdTemplate +
                   ", cpm=" + paidEvent.cpm +
                   ", winningPartner='" + paidEvent.winningPartner + '\'' +
                   ", winnerBidder='" + paidEvent.winningBidder + '\'' +
                   ", userId='" + paidEvent.userId + '\'' +
                   ", ifa='" + paidEvent.ifa + '\'' +
                   ", status='" + paidEvent.status + '\'' +
                   '}'

     );
   }
});

Sample App

Please have a look at our sample code to see how it all works: App.js

⚠️ **GitHub.com Fallback** ⚠️