活动一次又一次地加载



我正试图在日期到达时打开另一个活动,否则会显示日期剩余的秒数,但问题是当我运行应用程序时,它会一次又一次地加载同一页面。

但是当我从爆炸活动中运行时没有问题,但当我从倒计时活动中运行它时,随着日期的到来,爆炸活动会一次又一次地打开。我的意思是,未来的日期大于或等于给定的日期。

下面是倒计时活动:

public void countDownStart() {
handler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
handler.postDelayed(this, 1000);
// using try and catch for error handling
try {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd");

// Please here set your event date//YYYY-MM-DD
Date futureDate = dateFormat.parse("2021-04-12");

Date currentDate = new Date();
if (!currentDate.after(futureDate)) {
long diff = futureDate.getTime()
- currentDate.getTime();
long days = diff / (24 * 60 * 60 * 1000);
diff -= days * (24 * 60 * 60 * 1000);
long hours = diff / (60 * 60 * 1000);
diff -= hours * (60 * 60 * 1000);
long minutes = diff / (60 * 1000);
diff -= minutes * (60 * 1000);
long seconds = (diff / 1000)+(minutes*60)+(hours*60*60)+(days*60*60*60);
text1.setText("" + String.format(FORMAT, seconds));
} else {
Intent intent = new Intent(CountDown.this,BlastActivity.class);
startActivity(intent);
finish();
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
handler.postDelayed(runnable, 1 * 1000);
}

下面是爆破活动:

public class BlastActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
//        Playing audio on activity open
MediaPlayer birthday = MediaPlayer.create(BlastActivity.this, R.raw.birthday);
birthday.start();
super.onCreate(savedInstanceState);
setContentView(R.layout.blast);
// Delaying the next activity to be executed to wait for song finish
new Timer().schedule(new TimerTask() {
@Override
public void run() {
Intent intent = new Intent(BlastActivity.this, MainActivity.class);
birthday.stop();                // Song stopped when moving to next activity
startActivity(intent);
finish();
}
}, 20000);
}

}

这里是Android MainFest文件代码:

<activity android:name=".BlastActivity">
</activity>

<activity android:name=".CountDown" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity" android:launchMode="singleTask"/>

每当我打开应用程序时,Blast Activity就会一次又一次地加载。

在启动新的"活动"之前,您需要从处理程序中删除回调。你可以这样做

handler.removeCallbacksAndMessages(null);

问题是,尽管您破坏了"活动",但Handler仍在执行Runnable。最简单的解决方案是添加另一个实例变量,如下所示,

boolean terminateTimer = false;

并在将可运行程序发布到处理程序之前对此进行检查。

runnable = new Runnable() {
public void run() {
if (terminateTimer) // add this
return;
handler.postDelayed(this, 1000);
try {
...
else {
terminateTimer = true;
...
}
} catch (Exception e) { ... }
}
};

当需要停止计时器时,将该值更改为true

public void onDestroy() {
terminateTimer = true;
...
}

最新更新