gpt4 book ai didi

java - 以分钟和秒为单位的倒数计时器

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:18:08 28 4
gpt4 key购买 nike

这是一个倒数计时器,我想以分秒为单位进行打印。 ex(300000mili)5 分钟,然后数 4:60、4:59...这是我的部分代码

final MyCounter timer = new MyCounter(300000,1000);
blue.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
timer.start();
}
});
}
public class MyCounter extends CountDownTimer {

public MyCounter(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}

@Override
public void onFinish() {
blue.setText("Live");
}

@Override
public void onTick(long millisUntilFinished) {
blue.setText((millisUntilFinished/60000)+":"+(millisUntilFinished/5000));
// i tried this
}
}

当错过 20 秒时,我该如何设置振动?什么时候结束?谢谢,对不起我的英语不好

最佳答案

http://developer.android.com/reference/android/os/CountDownTimer.html

TextView _tv = (TextView) findViewById( R.id.textView1 );
new CountDownTimer(30000, 1000) { // adjust the milli seconds here

public void onTick(long millisUntilFinished) {
_tv.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() {
_tv.setText("done!");
}
}.start();

从 java 1.5 开始有 java.util.concurrent.TimeUnit 类

 _tv.setText(""+String.format("%d min, %d sec", 
TimeUnit.MILLISECONDS.toMinutes( millisUntilFinished),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/TimeUnit.html

TimeUnit 表示给定粒度单位的持续时间,并提供实用方法来跨单位转换,并在这些单位中执行计时和延迟操作。

对于低于 1.5 的 Java 版本或不完全支持 TimeUnit 类的系统,可以使用以下等式:

int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
int hours = (int) ((milliseconds / (1000*60*60)) % 24);

振动

 Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
v.vibrate(500);
<uses-permission android:name="android.permission.VIBRATE"/> // permission in manifest

编辑:

在 4 分 55 秒时振动 500 毫秒

 if((TimeUnit.MILLISECONDS.toMinutes( millisUntilFinished)==4) &&
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))==55)
{

Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
v.vibrate(500);
}

关于java - 以分钟和秒为单位的倒数计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17620641/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com