Monday, September 26, 2011

Re: [android-developers] unanswered topic: premature alarm problems


Hi,

On Tue, Sep 27, 2011 at 1:16 AM, Mark Murphy <mmurphy@commonsware.com> wrote:
On Mon, Sep 26, 2011 at 7:02 PM, John Goche <johngoche99@googlemail.com> wrote:
>> 1. Suppose I set the alarm for the first time for it to expire at a future
>> time.
>>     In this case it goes off immediately instead of after the del

You have a bug in your code, where you are supplying the wrong time.

If I change the line of code

alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() , pendingIntent);

to the following:

alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() * 1000 * 60, pendingIntent);

or even to the following

alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() * 1000 * 60 * 60, pendingIntent);

and recompile and run then the broadcast receiver still fires off immediately. There must be another answer...

> Anyone know what is wrong with the OP's code?

Presumably, hour and min are zero.

Also, setTimeInMillis() is redundant, as Calendar.getInstance() is
already initialized to the current time.

> No error messages in CatLog for this one.
> Just an immediate firing of the broadcast receiver.

Which means that you are setting the alarm time to the current time.

So then why the above?
 

Here is some sample code showing setting a recurring alarm to occur
every day at the same time, culled from a SharedPreference:

public static void setAlarm(Context ctxt) {
   AlarmManager mgr=(AlarmManager)ctxt.getSystemService(Context.ALARM_SERVICE);
   Calendar cal=Calendar.getInstance();
   SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(ctxt);
   String time=prefs.getString("alarm_time", "12:00");

   cal.set(Calendar.HOUR_OF_DAY, TimePreference.getHour(time));
   cal.set(Calendar.MINUTE, TimePreference.getMinute(time));
   cal.set(Calendar.SECOND, 0);
   cal.set(Calendar.MILLISECOND, 0);

   if (cal.getTimeInMillis()<System.currentTimeMillis()) {
     cal.add(Calendar.DAY_OF_YEAR, 1);
   }

   mgr.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
                     AlarmManager.INTERVAL_DAY,
                     getPendingIntent(ctxt));
 }


--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscribe@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

No comments:

Post a Comment