Android 当应用程序转到后台时,如何停止runnable?
我正在尝试建立一个runnable,它可以每隔5秒加载一次广告(当然5秒太快了,这只是为了测试) 这是我的密码:Android 当应用程序转到后台时,如何停止runnable?,android,background,runnable,Android,Background,Runnable,我正在尝试建立一个runnable,它可以每隔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 androi
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;
}
}
如果我按home按钮将应用程序隐藏到后台,runnable将以5秒的间隔继续加载广告
当应用程序隐藏在后台时,是否有任何方法停止runnable?非常感谢。只需使用
onPause()
当活动进入后台但尚未被终止时,作为活动生命周期的一部分调用
@Override
protected void onPause() {
handler.removeCallbacks(runnable);
super.onPause();
}
可选的
如果你想继续运行。只需覆盖onResume()
回调
@Override
protected void onResume()
{
handler.postDelayed(runnable, 5000);
super.onResume();
}
还要删除处理程序.postDelayed(runnable,5000)当应用程序在后台运行时,调用onCreate()
onPause()中的code>。删除onPause()中的可运行
onPause()
onStop()
可以放在那里的函数handler.removeCallbacks(runnable)代码>
您可以从这里获得更多信息顺便说一句,删除onCreate()中的handler.postDelayed(runnable,5000)后,应用程序运行得非常好,是因为我打开应用程序时,run()方法会启动吗?这样我就不需要用onCreate()再次调用handler了?在android系统调用onCreate()
之后,下一个将是onStart()
,然后是onResume()
。你可以在这里看到,如果他转移到另一个活动怎么办?他在那里是怎么做的?如果他换了别的活动怎么办?他是怎么做到的?@tony9099,还是一样的。在另一个活动进入前台之前,实际活动必须先进入后台。将调用onPause()。
protected void onPause() {
handler.removeCallbacks(runnable);
super.onPause();
}