如何在加载启动画面后显示插页式广告?

时间:2018-01-22 18:44:51

标签: android splash-screen ads interstitial

我需要帮助,我想在启动屏幕加载后显示插页式广告添加,但我的代码有错误。

这是我的代码:

public class SplashScreenActivity extends AppCompatActivity {

    InterstitialAd mInterstitialAd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_screen);

        // FIREBASE INTERSTICIAL
        mInterstitialAd = new InterstitialAd(this);
        mInterstitialAd.setAdUnitId("ca-app-pub-2565065222479596/3931476543");

        mInterstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdClosed() {
                requestNewInterstitial();
            }
        });

        requestNewInterstitial();

        Toast.makeText(this,"* Necessário Acesso a Internet *",Toast.LENGTH_LONG).show();

        Thread timerThread = new Thread() {
            public void run() {
                try {
                    sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {

                    if (mInterstitialAd.isLoaded()) {
                        mInterstitialAd.show();
                        Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
                        startActivity(intent);
                    }
                    else
                    {
                        Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
                    }
                }

            }
        };
        timerThread.start();

    }

    // FIREBASE INTERSTICIAL
    private void requestNewInterstitial() {
        AdRequest adRequest = new AdRequest.Builder()
                .addTestDevice("SEE_YOUR_LOGCAT_TO_GET_YOUR_DEVICE_ID")
                .build();

        mInterstitialAd.loadAd(adRequest);
    }

}
调试后,通知以下内容:

01-22 16:27:03.048 13840-13970/? E/AndroidRuntime: FATAL EXCEPTION: Thread-6
                                                   Process: idea.tisco.pepavideos, PID: 13840
                                                   java.lang.IllegalStateException: isLoaded must be called on the main UI thread.
                                                       at oc.b(:com.google.android.gms.DynamiteModulesA@11951448:20)
                                                       at com.google.android.gms.ads.internal.a.d(:com.google.android.gms.DynamiteModulesA@11951448:98)
                                                       at com.google.android.gms.ads.internal.client.ak.onTransact(:com.google.android.gms.DynamiteModulesA@11951448:14)
                                                       at android.os.Binder.transact(Binder.java:499)
                                                       at com.google.android.gms.internal.zzep$zza$zza.isReady(Unknown Source)
                                                       at com.google.android.gms.internal.zzfa.isLoaded(Unknown Source)
                                                       at com.google.android.gms.ads.InterstitialAd.isLoaded(Unknown Source)
                                                       at company.ts.SplashScreenActivity$2.run(SplashScreenActivity.java:50)

即使在调试之后我也无法理解错误的原因。

我想在启动画面之后或打开主要活动时显示插页式广告。

非常感谢你!

3 个答案:

答案 0 :(得分:2)

问题出在java.lang.IllegalStateException: isLoaded must be called on the main UI thread.

所以可能必须这样做

 runOnUiThread(new Runnable() {
    @Override public void run() {
        if (mInterstitialAd.isLoaded()) {
          mInterstitialAd.show();
     }
    }
});

可能你必须用活动参考来调用它,这取决于你在哪里打电话

 mYourActivity.runOnUiThread(new Runnable() {
    @Override public void run() {
        if (mInterstitialAd.isLoaded()) {
          mInterstitialAd.show();
     }
    }
});

来源:AdMob Interstitial and error isLoaded must be called on the main UI thread

答案 1 :(得分:0)

这是互联网上存在的最简单的方法。 在您的Splash活动的onCreate方法中添加下面的代码。

        InterstitialAd ad;

        ad = new InterstitialAd(this);
        ad.setAdUnitId(getString(R.string.interstitial));
        ad.loadAd(new AdRequest.Builder().build());

        ad.setAdListener(new AdListener(){
            @Override
            public void onAdClosed() {
                super.onAdClosed();
                startActivity(new Intent(getApplicationContext(), PermissionsActivity.class));
                finish();
            }
        });

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if(ad.isLoaded()) {
                    ad.show();
                }
                else{
                    startActivity(new Intent(getApplicationContext(), PermissionsActivity.class));
                    finish();
                }
            }
        }, 4000);

答案 2 :(得分:0)

初始屏幕上的Facebook非页内广告。

Build.Gradle:

implementation 'com.facebook.android:audience-network-sdk:5.+'
implementation 'com.victor:lib:1.0.4'

MyAplication.java:

AudienceNetworkAds.initialize(this);

Manifest.xml:

<activity
        android:name="com.facebook.ads.AudienceNetworkActivity"
        android:configChanges="keyboardHidden|orientation|screenSize" />

权限:

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

activity_splash.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_blue_light"
    tools:context=".SplashActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:textColor="@android:color/background_light"
        android:text="Splash Screen"
        android:textSize="25sp"
        android:layout_marginTop="20dp"
        android:textStyle="bold"/>

    <TextView
        android:id="@+id/loadingTxt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="Loading Ad..."
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="15dp"
        android:textColor="@android:color/holo_red_dark"/>

    <com.victor.loading.rotate.RotateLoading
        android:id="@+id/rotateloading"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_above="@+id/loadingTxt"
        app:loading_color="@android:color/holo_red_dark"
        android:layout_centerHorizontal="true"
        app:loading_speed="11"
        app:loading_width="5dp" />
</RelativeLayout>

SplashActivity.java

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.facebook.ads.Ad;
import com.facebook.ads.AdError;
import com.facebook.ads.InterstitialAd;
import com.facebook.ads.InterstitialAdListener;
import com.victor.loading.rotate.RotateLoading;

import java.lang.ref.WeakReference;

public class SplashActivity extends AppCompatActivity {


    private Handler handler;
    private SplashThread splashThread;

    private InterstitialAd facebookInterstitialAd;
    private boolean isAdsLoad=false;

    private TextView loadingTxt;
    private RotateLoading rotateloading;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //full screen
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_splash);

        loadingTxt=(TextView)findViewById(R.id.loadingTxt);
        rotateloading=(RotateLoading)findViewById(R.id.rotateloading);



        if (isNetworkAvailable(this)){
            //if on then load ads

            rotateloading.start();

            handler=new Handler();
            splashThread=new SplashThread(this);
            handler.postDelayed(splashThread,5000);  //5 second delay otherwise ads not show it take some time to load

            loadFaceBookAds();
        }
        else{
            //if network off then show simple splash screen

            rotateloading.setVisibility(View.GONE);
            loadingTxt.setVisibility(View.GONE);

            handler=new Handler();
            splashThread=new SplashThread(this);
            handler.postDelayed(splashThread,2000);  //2 second delay for simple splash
        }
    }

    public static boolean isNetworkAvailable(Context context) {

        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        if (null != connectivity) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (null != info && info.isConnected()) {
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
        return false;
    }

    private void loadFaceBookAds(){

        facebookInterstitialAd=new InterstitialAd(this,"Facebook_Interstitial_Ads_ID");
        facebookInterstitialAd.setAdListener(new InterstitialAdListener() {
            @Override
            public void onInterstitialDisplayed(Ad ad) {

            }

            @Override
            public void onInterstitialDismissed(Ad ad) {

                //on dismiss ads call next activity

                finish();
                startActivity(new Intent(SplashActivity.this,MainActivity.class));
            }

            @Override
            public void onError(Ad ad, AdError adError) {

            }

            @Override
            public void onAdLoaded(Ad ad) {

                //if ads load then show it.
                isAdsLoad=true;
                rotateloading.stop();
                rotateloading.setVisibility(View.GONE);
                loadingTxt.setVisibility(View.GONE);
                facebookInterstitialAd.show();
            }

            @Override
            public void onAdClicked(Ad ad) {

            }

            @Override
            public void onLoggingImpression(Ad ad) {

            }
        });

        facebookInterstitialAd.loadAd();
    }

    static class SplashThread implements Runnable{

        //Handle memory leakage..
        WeakReference<SplashActivity> weakReference;
        SplashThread(SplashActivity splashActivity){
            weakReference=new WeakReference<>(splashActivity);
        }
        @Override
        public void run() {

            SplashActivity mContext=weakReference.get();

            if (mContext==null)
                return;
            if (mContext.isFinishing())
                return;

            //if ads loaded no need to call next activity here.

            if (!mContext.isAdsLoad) {

                if (mContext.rotateloading.getVisibility()==View.VISIBLE) {
                    mContext.rotateloading.stop();
                    mContext.rotateloading.setVisibility(View.GONE);
                }
                mContext.finish();
                mContext.startActivity(new Intent(mContext, MainActivity.class));
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(splashThread);

        if (facebookInterstitialAd!=null)
            facebookInterstitialAd.destroy();
    }
}