在我的应用中,我有两项活动:主要活动和广告活动
在我的主要活动中,如果主活动中的特定持续时间(例如5秒)没有事件(按钮单击,列表视图单击,输入文本等),我想启动广告活动。
此代码在5秒后启动广告活动,但如果有活动,我想延迟它。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(MainActivity.this,AdsActivity.class);
MainActivity.this.startActivity(intent);
}
},5000);
}
所以我该怎么做?
答案 0 :(得分:1)
在事件发生时从处理程序中删除回调并发布新的runnable。这样的事情应该有效:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
postAdAfterDelay();
}
// Call this method when a valid event occurs
private void onEventOccurred() {
handler.removeCallbacksAndMessages(null);
postAdAfterDelay();
}
private void postAdAfterDelay() {
handler.postDelayed(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(MainActivity.this,AdsActivity.class);
MainActivity.this.startActivity(intent);
}
},5000);
}
答案 1 :(得分:1)
尝试这样的事情重启事件的5秒计时器:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
Intent intent = new Intent(MainActivity.this,AdsActivity.class);
MainActivity.this.startActivity(intent);
}
};
handler.postDelayed(runnable, 5000);
}
private void onYourEvent() {
handler.removeCallbacks(runnable);
handler.postDelayed(runnable, 5000);
}