timeLeft 用于播放音乐文件,但如何与onResume 一起使用? 所以我可以暂停 Activity ,然后使用剩余计时器继续。
这是我的代码:
public void countdownTimer () {
final TextView mTextField = (TextView)findViewById(R.id.timer);
Count = new CountDownTimer(TIMER, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("" +(millisUntilFinished / 60000));
long timeLeft = millisUntilFinished / 1000;
if(timeLeft <= 4 && timeLeft >=2 && tgbutton.isChecked())
{
mSoundPool.play(sixthMusicFile, 1f, 1f, 1, 0, 1f);
}
if(timeLeft <= 1 && tgbutton.isChecked())
{
mSoundPool.play(seventhMusicFile, 1f, 1f, 1, 0, 1f);
vibrate();
}
}
public void onFinish() {
Count.setText("done!");
}
}.start();
}
已编辑: 最后,我得到了一些答案。工作代码在这里: Android CountDown Timer with Pause, Resume and Cancel button . 非常感谢之前帮助过我的所有人。
最佳答案
试试这个 Activity :
public class MyActivity extends AppCompatActivity {
long TIMER = 1000000;
long timeLeft = 0;
private CountDownTimer Count;
SharedPreferences sharedPreferences;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedPreferences = getSharedPreferences("App_shared_preferenced", Context.MODE_PRIVATE);
}
@Override
protected void onResume() {
super.onResume();
timeLeft= sharedPreferences.getLong("leftTime",0);
if(timeLeft>0)
countdownTimer(timeLeft);
else countdownTimer(TIMER);
}
@Override
protected void onPause() {
super.onPause();
sharedPreferences.edit().putLong("leftTime",timeLeft).commit();
if(Count != null){
Count.cancel();
}
}
public void countdownTimer(long t) {
if(Count != null) Count.cancel();
final TextView mTextField = null;// Your text view
Count = new CountDownTimer(t, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("" + (millisUntilFinished / 60000));
timeLeft = millisUntilFinished / 1000;
if (timeLeft <= 4 && timeLeft >= 2 && tgbutton.isChecked()) {
mSoundPool.play(sixthMusicFile, 1f, 1f, 1, 0, 1f);
}
if (timeLeft <= 1 && tgbutton.isChecked()) {
mSoundPool.play(seventhMusicFile, 1f, 1f, 1, 0, 1f);
vibrate();
}
}
public void onFinish() {
Count.setText("done!");
timeLeft = 0;
}
}.start();
}
}
关于android - 如何在 Android 上使用 timeLeft 恢复倒计时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43950165/