Show “left time” until the alarm start

旧城冷巷雨未停 提交于 2019-12-11 08:20:23

问题


I whould like to create a alarm (AlarmManager) in Android. The alarm must show the left time until its finish.

So the user click on "set alarm at 11 pm" and see in a TextView "alarm in xy hours/minuts/seconds".

How can I achieve this?

Thanks.


回答1:


Try like this

    Calendar calendar = Calendar.getInstance();
    Long preTime = calendar.getTimeInMillis();

    // set alarm after 5 minute

    calendar.add(Calendar.MINUTE, 5);
    Long postTime = calendar.getTimeInMillis();
    Long delay = postTime - preTime;

    AlarmManager manager = (AlarmManager)     getSystemService(Context.ALARM_SERVICE);
    manager.set(AlarmManager.RTC_WAKEUP, postTime, null);

    CountDownTimer timer = new CountDownTimer(delay, 1) {

        @Override
        public void onTick(long millisUntilFinished) {
            final int seconds = (int) (millisUntilFinished / 1000) % 60;
            final int minutes = (int) ((millisUntilFinished / (1000 * 60)) % 60);

            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    text.setText("minute " + minutes + " Second " + seconds);
                }
            });
        }

        @Override
        public void onFinish() {
            // TODO Auto-generated method stub

        }
    };
    timer.start();



回答2:


//INIT
Calendar c = Calendar.getInstance();
int hNow = c.get(Calendar.HOUR_OF_DAY);    //get the Hour
int mNow = c.get(Calendar.MINUTE);         //get the Minute

int hAlarm = 8;       //your alarm Hour
int mAlarm = 30;      //your alarm Minute 

//FUNCTION

int timeLeft = (hAlarm * 60 + mAlarm) - (hNow * 60 + mNow);
if( timeLeft < 0 )
   timeLeft = 1440 + timeLeft;
int hLeft = timeLeft / 60;      //this is the hours left
int mLeft = timeLeft % 60;      //this is the minutes left


来源:https://stackoverflow.com/questions/22223893/show-left-time-until-the-alarm-start

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!