Вопрос

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.

Это было полезно?

Решение

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();

Другие советы

//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
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top