android studio做一个计时器,android studio怎么编写计时器
满意答案类似iOS中的NSTimer 定时器功能,开关控制随机几秒钟执行指定功能;平台:Android开发环境:android Studio代码实现:一. 创建Handler对象和Runnable对象[java] view plain copy print?Handler handler = new Handler();Runnable runnable = new Runnable() {@Ov
满意答案
类似iOS中的NSTimer 定时器功能,开关控制随机几秒钟执行指定功能;
平台:Android
开发环境:android Studio
代码实现:
一. 创建Handler对象和Runnable对象
[java] view plain copy print?
Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
if (mPageOpen){
if (interstitialAd.isLoaded()){ //示例-谷歌插页广告
interstitialAd.show();
}else {
AdRequest adRequest = new AdRequest.Builder().build();
interstitialAd.loadAd(adRequest);
}
int random = (int)(Math.random() * 10 +20)*1000; //随机时间循环执行
handler.postDelayed(this, random);
}
}
};
二. 开关控制
[java] view plain copy print?
Switch mSwith = (Switch) findViewById(R.id.switchPage);
mSwith.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mPageOpen = true;
} else {
mPageOpen = false;
}
handler.postDelayed(runnable, 15000); //开关控制执行
}
});
三. 移除定时器
[java] view plain copy print?
handler.removeCallbacks(runnable);
10分享举报
更多推荐
所有评论(0)