当应用程序进入后台时如何停止runnable?

Kit*_* Ng 10 android background 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 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;
    }

}
Run Code Online (Sandbox Code Playgroud)

如果我按主页按钮将应用程序隐藏到后台,则runnable将按照5秒的间隔加载广告.

当应用程序隐藏到后台时,有没有任何方法可以停止runnable?非常感谢.

小智 33

只需使用 onPause()

当活动进入后台但被(但)尚未被杀死时,被称为活动生命周期的一部分

@Override
protected void onPause() {
     handler.removeCallbacks(runnable);
     super.onPause();
}
Run Code Online (Sandbox Code Playgroud)

可选的

如果你想恢复那个可运行的.只需覆盖onResume()回调即可

@Override
protected void onResume()
{
      handler.postDelayed(runnable, 5000);
      super.onResume();
}
Run Code Online (Sandbox Code Playgroud)

同时删除handler.postDelayed(runnable, 5000);inonCreate()