Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

android - How to set an alarm to fire properly at fixed time?

I have this code

Calendar c = new GregorianCalendar();
        c.add(Calendar.DAY_OF_YEAR, 1);
        c.set(Calendar.HOUR_OF_DAY, 23);
        c.set(Calendar.MINUTE, 22);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);

        // We want the alarm to go off 30 seconds from now.
        long firstTime = SystemClock.elapsedRealtime();
        firstTime += 30*1000;
        long a=c.getTimeInMillis();

        // Schedule the alarm!
        AlarmManager am = (AlarmManager)ctx.getSystemService(Context.ALARM_SERVICE);
        am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                c.getTimeInMillis(), 1*60*60*1000, sender);

It is not executed at 23:22h

What I am doing wrong? I noticed firstTime and c.getTimeInMillis() differs a lot in size and length. When I use firstTime, so when set to 30 seconds, the alarm is executed well.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are using the AlarmManager.ELAPSED_REALTIME_WAKEUP flag, but you are using a Calendar object. These two things don't go together.

You need to use AlarmManager.RTC or AlarmManager.RTC_WAKEUP if you are specifying the alarm time using a Calendar or Date object (milliseconds since 1970).

You use AlarmManager.ELAPSED_REALTIME or AlarmManager.ELAPSED_REALTIME_WAKEUP when you are specifying the alarm time via SystemClock.elapsedRealtime() (milliseconds since the phone booted).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...