我是android新手。我有一个应用程序需要在textview中显示存储在数据库中的数据(这是一个时间值,例如40小时)。
我想将40(在我的情况下)的值倒数到零,并且当它达到零时应该开始报警。
答案 0 :(得分:0)
您可以使用CountDownTimer
对数值进行倒计时,如下所示:
final MyCounter timer = new MyCounter(600000, 1000); //add your time
...
public class MyCounter extends CountDownTimer
{
public MyCounter(long millisInFuture, long countDownInterval)
{
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish()
{
Log.i("debug","Timer Completed");
}
@Override
public void onTick(long millisUntilFinished)
{
tv.setText("Timer : " + (millisUntilFinished/60000) + " " + "minutes remaining.");
}
}
对于警报部分,您可以使用AlarmManager。这是一个tutorial。
希望它有所帮助!
答案 1 :(得分:0)
只需将剩余时间转换为秒(从db获取小时值并将其转换为秒,在我的情况下,我将在几秒钟内获得时间)
public class CountDownActivity extends Activity {
int time,initStart,startPointTime,hh,mm,ss,millis;
TextView txtSecond;
TextView txtMinute;
TextView txtHour;
TextView txtDay;
Handler handler;
long seconds =40*60*60;
Runnable updater;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
txtSecond=(TextView)findViewById(R.id.cntSecond);
txtMinute=(TextView)findViewById(R.id.cntMinute);
txtHour=(TextView)findViewById(R.id.cntHour);
txtDay=(TextView)findViewById(R.id.cntDay);
handler= new Handler();
initStart = (int) SystemClock.elapsedRealtime();
updater = new Runnable() {
public void run() {
int sec,minute,hour,day;
long diff = seconds;
System.out.println(diff);
if (diff >= 1) {
sec = (int) (diff%60);
} else {
sec=00;
}
txtSecond.setText("" +sec);
diff = diff/60;
System.out.println(diff);
if (diff >= 1) {
minute = (int) (diff%60);
} else {
minute=00;
}
txtMinute.setText("" +minute);
diff = diff/60;
if (diff >= 1) {
hour = (int) (diff%24);
} else {hour = 00; }
txtHour.setText("" +hour);
diff = diff/24;
if (diff >= 1) {
day = (int) diff;
} else { day =00; }
txtDay.setText("" +day);
seconds=seconds-1;
handler.postDelayed(this, 1000);
}
};
handler.post(updater);
}
> //and don't forget to removeCallback on destroy
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
handler.removeCallbacks(updater);
}
}