如何在Android上使用timeLeft进行简历countdowntimer?
问题描述:
timeLeft正在播放音乐文件,但如何使用onResume? 所以我可以暂停活动,然后用左定时器继续。如何在Android上使用timeLeft进行简历countdowntimer?
这里是我的代码:
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。非常感谢以前帮助我的每个人。
答
试试这个活动:
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();
}
}
你需要的是在这里:http://stackoverflow.com/a/10055480/5552022 –
谢谢回复@奥马尔 - aflak。但是让我很困惑。 – Bonnie7
基本上你需要的是一个CountDownTimer,你可以随时暂停/恢复,不是吗? –