我正在尝试创建一个具有计时器的应用程序,我已设法实现该计时器,并且如果未按下停止按钮,则在警报结束后十秒钟开始具有贪睡计时器倒计时。我一直试图解决这个问题已经好几天了,而且我显然做错了什么,但我仍然很新,并且还没有专业知识来解决这个问题。问题出现在我的第一个CountDownTimer的onFinish()方法中。警报响起后,屏幕将显示“出门时间!”在“if”语句中指定,但我的代码似乎永远不会进入我的代码的“else if”部分。我不知道这是不是因为我错误地写了代码的if / else if / else部分,或者因为我弄乱了计时器来计算出已经过了多少时间。任何帮助是极大的赞赏!谢谢!!!!
公共类CountDown扩展了ActionBarActivity {
private static long shower;
private static long snooze;
private Button stopButton;
private final long interval = 1 * 1000;
public TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_count_down);
Bundle extras = getIntent().getExtras();
shower = extras.getInt("EXTRA_SHOWER");
snooze = extras.getInt("EXTRA_SNOOZE");
final long showerMilli = shower * 60 * 1000;
final long snoozeMilli = snooze * 60 * 1000;
text = (TextView) findViewById(R.id.timeRemaining);
new CountDownTimer(showerMilli, interval) {
public void onTick(long millisUntilFinished) {
text.setText("" + String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
}
public void onFinish() {
text.setText("Time's up!");
MediaPlayer alarm = MediaPlayer.create(CountDown.this, R.raw.alarmsound);
alarm.start();
long timeElapsed = SystemClock.currentThreadTimeMillis();
long alarmTime = timeElapsed-showerMilli;
if (alarmTime <= 10000) {
text.setText("Time to get out!");
timeElapsed=SystemClock.currentThreadTimeMillis();
alarmTime = timeElapsed-showerMilli;
}
else if (alarmTime > 10000) {
alarm.stop();
new CountDownTimer(snoozeMilli, interval) {
public void onTick(long millisUntilFinished) {
text.setText("" + String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
}
public void onFinish() {
text.setText("Snooze is done!");
}
}.start();
}
else {
return;
}
}
}.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_count_down, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}