android – 如何每隔X秒显示插页式广告
作者:互联网
我需要每隔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());
}
}
解决方法:
您的活动似乎在后台,然后用户可以看到广告,因为一旦您的活动被销毁,您的广告就无法展示,没有此上下文没有活动.
第一:在onCreate之外保留对ScheduledExecutorService的引用
第二:覆盖onStop并调用scheduler.shutdownNow().
onStop:当您的活动进入后台状态时,将调用它
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;
}
}
标签:android,android-studio,ads,interstitial 来源: https://codeday.me/bug/20190627/1305406.html