Implementação

Mediação AdMob e StartApp

Implementação mediação AdMob e StartApp no android studio

Strings

<resources>
    <string name="app_name">StartApp Java</string>




                <!-- Ids Mediação Teste  -->
    <!-- app_id: ca-app-pub-4237896427435354~2081366453 -->
    <!-- bannerId: ca-app-pub-4237896427435354/3975836391 -->
    <!-- interticialId: ca-app-pub-4237896427435354/7549315550 -->
    <!-- rewardsId: ca-app-pub-4237896427435354/3993756493 -->
    <!-- mrecId ca-app-pub-4237896427435354/3333401580 -->
    <!-- nativeId: ca-app-pub-4237896427435354/4302971589 -->

    <string name="appId">ca-app-pub-4237896427435354~2081366453</string>
    <string name="bannerId">ca-app-pub-4237896427435354/3975836391</string>
    <string name="interstitialId">ca-app-pub-4237896427435354/7549315550</string>
    <string name="rewardedId">ca-app-pub-4237896427435354/3993756493</string>
    <string name="mrecId">ca-app-pub-4237896427435354/3333401580</string>
    <string name="nativeId">ca-app-pub-4237896427435354/4302971589</string>



</resources>

<manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.StartAppJava"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- Sample AdMob app ID: ca-app-pub-3940256099942544~3347511713 -->
        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="@string/appId"/>

    </application>

</manifest>

buid.gradle.kts a nivel de app

   // Mediação AdMob StartApp
    implementation ("com.google.android.gms:play-services-ads:22.5.0")
    implementation("com.startapp:admob-mediation:2.+")
    implementation("com.startapp:admob-mediation:2.+")

MainActivity.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/interstitial_load_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:onClick="onClickLoadInterstitial"
        android:text="Load Interstitial"
        app:layout_constraintEnd_toStartOf="@+id/interstitial_show_button"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/interstitial_show_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:enabled="false"
        android:onClick="onClickShowInterstitial"
        android:text="Show Interstitial"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/interstitial_load_button"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/banner_load_button"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:onClick="onClickLoadBanner"
        android:text="Load Banner"
        app:layout_constraintEnd_toEndOf="@+id/interstitial_load_button"
        app:layout_constraintStart_toStartOf="@+id/interstitial_load_button"
        app:layout_constraintTop_toBottomOf="@+id/interstitial_load_button" />

    <Button
        android:id="@+id/rewarded_load_button"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:onClick="onClickLoadRewarded"
        android:text="Load Rewarded"
        app:layout_constraintEnd_toEndOf="@+id/mrec_load_button"
        app:layout_constraintStart_toStartOf="@+id/mrec_load_button"
        app:layout_constraintTop_toBottomOf="@+id/mrec_load_button" />

    <Button
        android:id="@+id/rewarded_show_button"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:enabled="false"
        android:onClick="onClickShowRewarded"
        android:text="Show Rewarded"
        app:layout_constraintBottom_toBottomOf="@+id/rewarded_load_button"
        app:layout_constraintEnd_toEndOf="@+id/interstitial_show_button"
        app:layout_constraintStart_toStartOf="@+id/interstitial_show_button" />

    <Button
        android:id="@+id/native_load_button"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:onClick="onClickLoadNative"
        android:text="Load Native"
        app:layout_constraintEnd_toEndOf="@+id/rewarded_load_button"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="@+id/rewarded_load_button"
        app:layout_constraintTop_toBottomOf="@+id/rewarded_load_button" />

    <Button
        android:id="@+id/native_show_button"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:enabled="false"
        android:onClick="onClickShowNative"
        android:text="Show Native"
        app:layout_constraintBottom_toBottomOf="@+id/native_load_button"
        app:layout_constraintEnd_toEndOf="@+id/rewarded_show_button"
        app:layout_constraintStart_toStartOf="@+id/rewarded_show_button" />

    <FrameLayout
        android:id="@+id/native_ad_placeholder"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/native_load_button"/>

    <Button
        android:id="@+id/mrec_load_button"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:onClick="onClickLoadMrec"
        android:text="Load Medium"
        app:layout_constraintEnd_toEndOf="@+id/banner_load_button"
        app:layout_constraintHorizontal_bias="0.454"
        app:layout_constraintStart_toStartOf="@+id/banner_load_button"
        app:layout_constraintTop_toBottomOf="@+id/banner_load_button" />

</androidx.constraintlayout.widget.ConstraintLayout>

native_ad_unified.xml

<?xml version="1.0" encoding="utf-8"?>
<com.google.android.gms.ads.nativead.NativeAdView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/nativeView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#E3F2FD"
        android:orientation="vertical">

        <TextView
            android:id="@+id/call_to_action_text_view"
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:text="%Call 2 Action%" />

        <TextView
            android:id="@+id/headline_text_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:text="%headline%"
            android:textAppearance="@style/TextAppearance.AppCompat.Medium" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="end"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/store_text_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginRight="10dp"
                android:text="%Store%" />

            <TextView
                android:id="@+id/rating_text_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginRight="10dp"
                android:text="%Rating%" />

            <TextView
                android:id="@+id/price_text_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginRight="10dp"
                android:text="%Price%" />

            <TextView
                android:id="@+id/advertiser_text_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginRight="10dp"
                android:text="%Advertisier%"
                android:textStyle="bold" />

            <ImageView
                android:id="@+id/logo_image_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:adjustViewBounds="true"
                android:maxHeight="50dp"
                app:srcCompat="@android:mipmap/sym_def_app_icon" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/image_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:adjustViewBounds="true"
                android:maxHeight="50dp"
                app:srcCompat="@android:mipmap/sym_def_app_icon" />

            <com.google.android.gms.ads.nativead.MediaView
                android:id="@+id/media_view"
                android:layout_width="wrap_content"
                android:layout_height="50dp"
                android:adjustViewBounds="false"
                android:background="#00BCD4" />

        </LinearLayout>

        <TextView
            android:id="@+id/body_text_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="%Body%" />

    </LinearLayout>

</com.google.android.gms.ads.nativead.NativeAdView>

MainActivity.kt

package com.app.startappjava;

import static com.startapp.mediation.admob.BuildConfig.DEBUG;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.Toast;

import com.app.startappjava.databinding.ActivityMainBinding;
import com.app.startappjava.databinding.NativeAdUnifiedBinding;
import com.google.android.gms.ads.AdLoader;



import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintSet;
import androidx.core.view.ViewCompat;

import com.google.android.gms.ads.AdError;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdLoader;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdValue;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.FullScreenContentCallback;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.OnPaidEventListener;
import com.google.android.gms.ads.OnUserEarnedRewardListener;
import com.google.android.gms.ads.interstitial.InterstitialAd;
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback;
import com.google.android.gms.ads.nativead.NativeAd;
import com.google.android.gms.ads.nativead.NativeAdView;
import com.google.android.gms.ads.rewarded.RewardItem;
import com.google.android.gms.ads.rewarded.RewardedAd;
import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback;
import com.startapp.mediation.admob.StartappAdapter;
import com.startapp.sdk.adsbase.StartAppSDK;

import java.util.List;
public class MainActivity extends AppCompatActivity {
    private static final boolean USE_TEST_SUITE = false;
    @Nullable
    private static Boolean initialized;
    private ActivityMainBinding viewBinding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
      //  setContentView(R.layout.activity_main);
        viewBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(viewBinding.getRoot());









        if (initialized == null) {
            initialized = false;

            MobileAds.initialize(this, status -> {
                initialized = true;

                Toast.makeText(this, "Initialization complete", Toast.LENGTH_SHORT).show();

                initBanner();
                initMrec();

                if (USE_TEST_SUITE) {
               //     MediationTestSuite.launch(MainActivity.this);
                }
            });

            if (DEBUG) {
                StartAppSDK.setTestAdsEnabled(true);
            }
        }
    }

    //region Banner
    @Nullable
    private AdView banner;

    private void initBanner() {
        final ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);

        banner = new AdView(this);
        banner.setAdUnitId(getString(R.string.bannerId));
        banner.setAdSize(AdSize.BANNER);
        banner.setId(ViewCompat.generateViewId());
        viewBinding.layout.addView(banner, params);

        final ConstraintSet constraints = new ConstraintSet();
        constraints.clone(viewBinding.layout);
        constraints.connect(banner.getId(), ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM);
        constraints.centerHorizontally(banner.getId(), ConstraintSet.PARENT_ID);
        constraints.applyTo(viewBinding.layout);

        banner.setAdListener(new AdListener() {
            @Override
            public void onAdFailedToLoad(@NonNull LoadAdError error) {
                Toast.makeText(MainActivity.this, "Load failed, " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onAdLoaded() {
                Toast.makeText(MainActivity.this, "Banner - onAdLoaded", Toast.LENGTH_SHORT).show();

                if (mrec != null && mrec.getVisibility() == View.VISIBLE) {
                    mrec.setVisibility(View.GONE);
                }

                banner.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAdOpened() {
                Toast.makeText(MainActivity.this, "Banner - onAdOpened", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onAdClosed() {
                Toast.makeText(MainActivity.this, "Banner - onAdClosed", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onAdClicked() {
                Toast.makeText(MainActivity.this, "Banner - onAdClicked", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onAdImpression() {
                Toast.makeText(MainActivity.this, "Banner - onAdImpression", Toast.LENGTH_SHORT).show();
            }
        });

        // prevent navite ad view covering
        banner.setVisibility(View.GONE);
    }

    /**
     * you can as well write to admob network custom event interface optional parameter
     * which must be in json format, unused fields can be omitted:
     * {startappAppId:'204653131', adTag:'bannerTagFromServer', minCPM:0.02, is3DBanner:false}
     * each value from the admob interface overrides corresponding value from the extras bundle
     */
    public void onClickLoadBanner(@NonNull View view) {
        if (!Boolean.TRUE.equals(initialized)) {
            return;
        }

        if (banner == null) {
            return;
        }

        // optionally you can set additional parameters for Startapp banner
        final Bundle extras = new StartappAdapter.Extras.Builder()
                .setAdTag("bannerTagFromAdRequest")
                .enable3DBanner()
                .setMinCPM(0.01)
                .toBundle();

        banner.loadAd(new AdRequest.Builder()
                .addNetworkExtrasBundle(StartappAdapter.class, extras)
                .build());
    }
    //endregion

    //region Medium Rectangle
    @Nullable
    private AdView mrec;

    private void initMrec() {
        final ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);

        mrec = new AdView(this);
        mrec.setAdUnitId(getString(R.string.mrecId));
        mrec.setAdSize(AdSize.MEDIUM_RECTANGLE);
        mrec.setId(ViewCompat.generateViewId());
        viewBinding.layout.addView(mrec, params);

        final ConstraintSet constraints = new ConstraintSet();
        constraints.clone(viewBinding.layout);
        constraints.connect(mrec.getId(), ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM);
        constraints.centerHorizontally(mrec.getId(), ConstraintSet.PARENT_ID);
        constraints.applyTo(viewBinding.layout);

        mrec.setAdListener(new AdListener() {
            @Override
            public void onAdFailedToLoad(@NonNull LoadAdError error) {
                Toast.makeText(MainActivity.this, "Mrec load failed, " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onAdLoaded() {
                Toast.makeText(MainActivity.this, "Mrec - onAdLoaded", Toast.LENGTH_SHORT).show();

                if (banner != null && banner.getVisibility() == View.VISIBLE) {
                    banner.setVisibility(View.GONE);
                }

                mrec.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAdOpened() {
                Toast.makeText(MainActivity.this, "Mrec - onAdOpened", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onAdClosed() {
                Toast.makeText(MainActivity.this, "Mrec - onAdClosed", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onAdClicked() {
                Toast.makeText(MainActivity.this, "Mrec - onAdClicked", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onAdImpression() {
                Toast.makeText(MainActivity.this, "Mrec - onAdImpression", Toast.LENGTH_SHORT).show();
            }
        });

        // prevent navite ad view covering
        mrec.setVisibility(View.GONE);
    }

    /**
     * you can as well write to admob network custom event interface optional parameter
     * which must be in json format, unused fields can be omitted:
     * {startappAppId:'204653131', adTag:'mrecTagFromServer', minCPM:0.02, is3DBanner:false}
     * each value from the admob interface overrides corresponding value from the extras bundle
     */
    public void onClickLoadMrec(@NonNull View view) {
        if (!Boolean.TRUE.equals(initialized)) {
            return;
        }

        if (mrec == null) {
            return;
        }

        // optionally you can set additional parameters for Startapp banner
        final Bundle extras = new StartappAdapter.Extras.Builder()
                .setAdTag("mrecTagFromAdRequest")
                .enable3DBanner()
                .setMinCPM(0.01)
                .toBundle();

        mrec.loadAd(new AdRequest.Builder()
                .addNetworkExtrasBundle(StartappAdapter.class, extras)
                .build());
    }
    //endregion

    //region Interstitial
    @Nullable
    private InterstitialAd interstitial;

    /**
     * you can as well write to admob network custom event interface optional parameter
     * which must be in json format, unused by you fields can be omitted:
     * {startappAppId:'204653131', adTag:'interstitialTagFromServer', interstitialMode:'OVERLAY', minCPM:0.02, muteVideo:false}
     * each value from the admob interface overrides corresponding value from the extras map
     */
    public void onClickLoadInterstitial(@NonNull View view) {
        if (!Boolean.TRUE.equals(initialized)) {
            return;
        }

        // optionally you can set additional parameters for Startapp interstitial
        final Bundle extras = new StartappAdapter.Extras.Builder()
                .setAdTag("interstitialTagFromAdRequest")
                .setInterstitialMode(StartappAdapter.Mode.OFFERWALL)
                .muteVideo()
                .setMinCPM(0.01)
                .toBundle();

        final AdRequest request = new AdRequest.Builder()
                .addNetworkExtrasBundle(StartappAdapter.class, extras)
                .build();

        InterstitialAd.load(this, getString(R.string.interstitialId), request, new InterstitialAdLoadCallback() {
            @Override
            public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
                // The interstitial reference will be null until
                // an ad is loaded.
                interstitial = interstitialAd;
                setupInterstitialDisplayCallbacks();

                viewBinding.interstitialShowButton.setEnabled(true);
            }

            @Override
            public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                // Handle the error
                Toast.makeText(MainActivity.this, "interstitial load failed, " + loadAdError.getMessage(), Toast.LENGTH_SHORT).show();
                interstitial = null;
            }
        });
    }

    private void setupInterstitialDisplayCallbacks() {
        if (interstitial == null) {
            return;
        }

        interstitial.setFullScreenContentCallback(new FullScreenContentCallback() {
            @Override
            public void onAdDismissedFullScreenContent() {
                // Called when fullscreen content is dismissed.
                Toast.makeText(MainActivity.this, "interstitial - onAdDismissedFullScreenContent", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onAdFailedToShowFullScreenContent(@NonNull AdError adError) {
                // Called when fullscreen content failed to show.
                Toast.makeText(MainActivity.this, "interstitial - onAdFailedToShowFullScreenContent, " + adError.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onAdShowedFullScreenContent() {
                // Called when fullscreen content is shown.
                // Make sure to set your reference to null so you don't
                // show it a second time.
                Toast.makeText(MainActivity.this, "interstitial - onAdShowedFullScreenContent", Toast.LENGTH_SHORT).show();

                interstitial = null;
            }
        });

        interstitial.setOnPaidEventListener(new OnPaidEventListener() {
            @Override
            public void onPaidEvent(@NonNull AdValue adValue) {
                Toast.makeText(MainActivity.this, "interstitial - setOnPaidEventListener", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void onClickShowInterstitial(@NonNull View view) {
        if (!Boolean.TRUE.equals(initialized)) {
            return;
        }

        if (interstitial == null) {
            return;
        }

        view.setEnabled(false);

        interstitial.show(this);
    }
    //endregion

    //region Rewarded
    @Nullable
    private RewardedAd rewarded;

    /**
     * you can as well write to admob network custom event interface optional parameter
     * which must be in json format, unused by you fields can be omitted:
     * {startappAppId:'204653131', adTag:'rewardedTagFromServer', minCPM:0.02, muteVideo:false}
     * each value from the admob interface overrides corresponding value from the extras map
     */
    public void onClickLoadRewarded(@NonNull View view) {
        if (!Boolean.TRUE.equals(initialized)) {
            return;
        }

        // optionally you can set additional parameters for Startapp interstitial
        final Bundle extras = new StartappAdapter.Extras.Builder()
                .setAdTag("rewardedTagFromAdRequest")
                .muteVideo()
                .setMinCPM(0.01)
                .toBundle();

        final AdRequest adRequest = new AdRequest.Builder()
                .addNetworkExtrasBundle(StartappAdapter.class, extras)
                .build();

        RewardedAd.load(this, getString(R.string.rewardedId), adRequest, new RewardedAdLoadCallback() {
            @Override
            public void onAdLoaded(@NonNull RewardedAd rewardedAd) {
                rewarded = rewardedAd;
                viewBinding.rewardedShowButton.setEnabled(true);
            }

            @Override
            public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                viewBinding.rewardedShowButton.setEnabled(false);
                Toast.makeText(MainActivity.this, "Load failed: " + loadAdError, Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void onClickShowRewarded(@NonNull View view) {
        if (!Boolean.TRUE.equals(initialized)) {
            return;
        }

        if (rewarded == null) {
            return;
        }

        view.setEnabled(false);

        rewarded.setFullScreenContentCallback(new FullScreenContentCallback() {
            @Override
            public void onAdFailedToShowFullScreenContent(@NonNull AdError adError) {
                Toast.makeText(MainActivity.this, "rewarded - onAdFailedToShowFullScreenContent: " + adError, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onAdShowedFullScreenContent() {
                rewarded = null;
                Toast.makeText(MainActivity.this, "rewarded - onAdShowedFullScreenContent", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onAdDismissedFullScreenContent() {
                rewarded = null;
                Toast.makeText(MainActivity.this, "rewarded - onAdDismissedFullScreenContent", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onAdImpression() {
                Toast.makeText(MainActivity.this, "rewarded - onAdImpression", Toast.LENGTH_SHORT).show();
            }
        });

        rewarded.show(this, new OnUserEarnedRewardListener() {
            @Override
            public void onUserEarnedReward(@NonNull RewardItem rewardItem) {
                Toast.makeText(MainActivity.this, "rewarded - onUserEarnedReward: type=" + rewardItem.getType() + " amount=" + rewardItem.getAmount(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    //endregion

    //region Native
    @Nullable
    private NativeAd nativeAdObject;

  /*
     you can as well write to admob network custom event interface optional parameter
     which must be in json format, unused fields can be omitted:
     {startappAppId:'204653131', adTag:'nativeTagFromServer', minCPM:0.02, nativeImageSize:'SIZE340X340', nativeSecondaryImageSize:'SIZE72X72'}
      each value from the admob interface overrides corresponding value from the extras map

   */
    public void onClickLoadNative(@NonNull View view) {
        if (!Boolean.TRUE.equals(initialized)) {
            return;
        }

        // clear previous ad
        viewBinding.nativeAdPlaceholder.removeAllViews();

        final AdLoader loader = new AdLoader.Builder(this, getString(R.string.nativeId))
                .forNativeAd(new NativeAd.OnNativeAdLoadedListener() {
                    @Override
                    public void onNativeAdLoaded(@NonNull NativeAd nativeAd) {
                        nativeAdObject = nativeAd;
                        viewBinding.nativeShowButton.setEnabled(true);
                    }
                })
                .withAdListener(new AdListener() {
                    @Override
                    public void onAdFailedToLoad(@NonNull LoadAdError adError) {
                        viewBinding.nativeShowButton.setEnabled(false);

                        Toast.makeText(MainActivity.this, "Load failed: " + adError, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onAdOpened() {
                        Toast.makeText(MainActivity.this, "native - onAdOpened", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onAdClosed() {
                        Toast.makeText(MainActivity.this, "native - onAdClosed", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onAdClicked() {
                        Toast.makeText(MainActivity.this, "native - onAdClicked", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onAdImpression() {
                        Toast.makeText(MainActivity.this, "native - onAdImpression", Toast.LENGTH_SHORT).show();
                    }
                })
                .build();

        // optionally you can set additional parameters
        final Bundle extras = new StartappAdapter.Extras.Builder()
                .setAdTag("nativeTagFromAdRequest")
                .setMinCPM(0.01)
                .setNativeImageSize(StartappAdapter.Size.SIZE150X150)
                .setNativeSecondaryImageSize(StartappAdapter.Size.SIZE100X100)
                .toBundle();

        loader.loadAd(new AdRequest.Builder()
                .addNetworkExtrasBundle(StartappAdapter.class, extras)
                .build());
    }

    public void onClickShowNative(@NonNull View view) {
        if (!Boolean.TRUE.equals(initialized)) {
            return;
        }

        final NativeAdUnifiedBinding adUnifiedBinding = NativeAdUnifiedBinding.inflate(getLayoutInflater());
        populateNativeAdView(adUnifiedBinding.nativeView, adUnifiedBinding);

        viewBinding.nativeAdPlaceholder.addView(adUnifiedBinding.getRoot());

        view.setEnabled(false);
    }

    private void populateNativeAdView(@NonNull NativeAdView adView, @NonNull NativeAdUnifiedBinding unifiedBinding) {
        if (nativeAdObject == null) {
            return;
        }

        unifiedBinding.headlineTextView.setText(nativeAdObject.getHeadline());
        adView.setHeadlineView(unifiedBinding.headlineTextView);

        // the asset is populated automatically, so there's one less step
        adView.setMediaView(unifiedBinding.mediaView);

        final List<NativeAd.Image> images = nativeAdObject.getImages();
        if (images.size() > 0) {
            unifiedBinding.imageView.setImageDrawable(images.get(0).getDrawable());
            adView.setImageView(unifiedBinding.imageView);
        }

        unifiedBinding.callToActionTextView.setText(nativeAdObject.getCallToAction());
        adView.setCallToActionView(unifiedBinding.callToActionTextView);

        unifiedBinding.bodyTextView.setText(nativeAdObject.getBody());
        adView.setBodyView(unifiedBinding.bodyTextView);

        unifiedBinding.advertiserTextView.setText(nativeAdObject.getAdvertiser());
        adView.setAdvertiserView(unifiedBinding.advertiserTextView);

        final NativeAd.Image image = nativeAdObject.getIcon();
        if (image != null) {
            unifiedBinding.logoImageView.setImageDrawable(image.getDrawable());
            adView.setIconView(unifiedBinding.logoImageView);
        }

        final String price = nativeAdObject.getPrice();
        if (price != null) {
            unifiedBinding.priceTextView.setText(price);
            adView.setPriceView(unifiedBinding.priceTextView);
        }

        final Double rating = nativeAdObject.getStarRating();
        if (rating != null) {
            unifiedBinding.ratingTextView.setText(String.valueOf(rating));
            adView.setStarRatingView(unifiedBinding.ratingTextView);
        }

        final String store = nativeAdObject.getStore();
        if (store != null) {
            unifiedBinding.storeTextView.setText(store);
            adView.setStoreView(unifiedBinding.storeTextView);
        }

        adView.setNativeAd(nativeAdObject);

    }
}

Se você tiver alguma crítica construtiva ou sugestão específica, ficarei feliz em ouvir e tentar melhorar.

0 / 5 Resultados 0 Votos 0

Classificação da sua página:

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

Botão Voltar ao topo
Fechar

Adblock detectado

Please consider supporting us by disabling your ad blocker!