如何每 X 秒显示插页式广告

How to Show Interstitial Ad every X Seconds

我需要每隔 x 秒在我的应用程序中显示插页式广告。我已经关闭了这段代码。它工作正常,但问题是,即使应用程序关闭,插页式广告仍然出现。

如何在应用程序关闭时停止此操作?

谢谢。

public class MainActivity extends AppCompatActivity {

    private InterstitialAd mInterstitialAd;

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

        prepareAd();

        ScheduledExecutorService scheduler =
                Executors.newSingleThreadScheduledExecutor();

        scheduler.scheduleAtFixedRate(new Runnable() {
            public void run() {
                Log.i("hello", "world");
                runOnUiThread(new Runnable() {
                    public void run() {
                        if (mInterstitialAd.isLoaded()) {
                            mInterstitialAd.show();
                        } else {
                           Log.d("TAG"," Interstitial not loaded");
                        }

                        prepareAd();
                    }
                });
            }
        }, 10, 10, TimeUnit.SECONDS);
    }

    public void  prepareAd() {
        mInterstitialAd = new InterstitialAd(this);
        mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
        mInterstitialAd.loadAd(new AdRequest.Builder().build());
    }
}

好像你的 activity 在后台,然后用户将能够看到广告,因为一旦你的 activity 被销毁,你的广告将无法显示,不 this 上下文编号 activity.

首先:在 onCreate

之外保留对 ScheduledExecutorService 的引用

第二:重写 onStop 并调用 scheduler.shutdownNow().

onStop : 当你的 activity 进入后台状态时会被调用

shutdownNow() : 将尝试停止当前 运行 任务并停止等待任务的执行

因此即使您的应用程序处于后台,这也会停止执行程序

public class MainActivity extends AppCompatActivity {

    private InterstitialAd mInterstitialAd;
    private ScheduledExecutorService scheduler;
    private boolean isVisible;

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


    @Override
    protected void onStart(){
    super.onStart();
        isVisible = true;
        if(scheduler == null){
            scheduler = Executors.newSingleThreadScheduledExecutor();
            scheduler.scheduleAtFixedRate(new Runnable() {
        public void run() {
            Log.i("hello", "world");
            runOnUiThread(new Runnable() {
                public void run() {
                    if (mInterstitialAd.isLoaded() && isVisible) {
                        mInterstitialAd.show();
                    } else {
                       Log.d("TAG"," Interstitial not loaded");
                    }

                    prepareAd();
                }
            });
        }
    }, 10, 10, TimeUnit.SECONDS);

        }

    }    
    //.. code 

    @Override
    protected void onStop() {
        super.onStop();
        scheduler.shutdownNow();
        scheduler = null;
        isVisible =false;
   }

}