当应用程序进入后台时如何停止可运行? [英] How to stop runnable when the app goes to background?

查看:137
本文介绍了当应用程序进入后台时如何停止可运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试建立一个可运行的设备,该设备可以每5秒钟间隔加载一次广告(当然5秒钟太快了,这只是出于测试目的)

I am trying to establish a runnable which can load ads by every 5 sec interval (of course 5 sec is too fast, it's just for testing purpose)

这是我的代码:

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秒的间隔不断加载广告.

If I press home button to hide the app to the background, the runnable keeps loading ads by 5 sec interval.

在后台隐藏应用程序时,是否有任何方法可以停止运行?非常感谢.

Is there any method to stop runnable when an app is hidden to the background? Many thanks.

推荐答案

只需使用onPause()

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

Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed

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

可选

如果要恢复该可运行文件.只需覆盖onResume()回调

If you want to resume that runnable. Just override the onResume() callback

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

还删除onCreate()

这篇关于当应用程序进入后台时如何停止可运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆