【发布时间】:2021-07-07 04:36:21
【问题描述】:
我正在尝试在日期到达时打开另一个活动,否则会显示剩余的日期秒数,但问题是当我运行应用程序时,它会一次又一次地加载相同的页面。
但是当我从爆破活动中运行时没有问题,但是当我从倒计时活动中运行时,爆破活动会随着日期的到来而一次又一次地打开。我的意思是未来日期大于或等于给定日期。
下面是倒计时活动:
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);
-
非常感谢...您的想法奏效了。我努力了好几天终于解决了。
-
我写了一个答案。接受它,这样每个人都可以知道正确的答案
标签: java android android-intent android-activity