【问题标题】:How to show interstitial ad after loading the splash screen?加载启动画面后如何显示插页式广告?
【发布时间】:2018-01-22 18:44:50
【问题描述】:

我需要帮助,我想在初始屏幕加载后显示一个插页式添加,但我的代码有错误。

这是我的代码:

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)

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

我只想在初始屏幕之后或打开 mainactivity 时显示一个插页式广告。

非常感谢!

【问题讨论】:

  • 您希望在启动画面结束后显示广告,那么您应该在我的意思是在您的 mainActivity 的 ON CREATE 中使用插页式广告加载和显示过程

标签: android splash-screen ads interstitial


【解决方案1】:

问题出在这里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

【讨论】:

    【解决方案2】:

    闪屏上的 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();
        }
    }
    

    【讨论】:

      【解决方案3】:

      这是互联网上最简单的方法。 在 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);
      

      【讨论】:

      • 它会抛出异常,因为“ad.isLoaded()”方法仅适用于 UI 线程。
      猜你喜欢
      • 2017-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-09
      相关资源
      最近更新 更多