gpt4 book ai didi

android - 当应用程序进入后台时如何停止运行?

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:53:05 25 4
gpt4 key购买 nike

我正在尝试建立一个可以每 5 秒加载一次广告的可运行程序(当然 5 秒太快了,它只是为了测试目的)

这是我的代码:

package com.admobsdk_dfp_handler;

import com.google.ads.*;
import com.google.ads.doubleclick.*;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.view.Menu;
import android.widget.RelativeLayout;

public class AdMobSDK_DFP_Handler extends Activity {
private DfpAdView adView;
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {

public void run() {
adView.loadAd(new AdRequest());
handler.postDelayed(this, 5000);
}
};

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

adView = new DfpAdView(
this,
AdSize.BANNER,
AD_UNIT_ID);

RelativeLayout layout = (RelativeLayout) findViewById(R.id.mainLayout);

layout.addView(adView);

adView.loadAd(new AdRequest());

handler.postDelayed(runnable, 5000);


};

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


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_ad_mob_sdk__dfp__handler,
menu);
return true;
}

}

如果我按主页按钮将应用程序隐藏到后台,可运行程序会以 5 秒的间隔持续加载广告。

当应用程序隐藏到后台时,有什么方法可以停止运行吗?非常感谢。

最佳答案

只需使用 onPause()

当 Activity 进入后台但尚未(尚未)被杀死时,作为 Activity 生命周期的一部分调用

@Override
protected void onPause() {
handler.removeCallbacks(runnable);
super.onPause();
}

可选

如果你想恢复那个runnable。只需覆盖 onResume() 回调

@Override
protected void onResume()
{
handler.postDelayed(runnable, 5000);
super.onResume();
}

同时删除 onCreate() 中的 handler.postDelayed(runnable, 5000);

关于android - 当应用程序进入后台时如何停止运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13560243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com