Monday, September 26, 2011

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

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.

>> 2. Every other time following the first time I set the alarm again for it
>> to expire at some future time
>>     it again goes off immediately, but this time displaying the data in
>> the parcel I passed to it the first time.

See above.

> http://stackoverflow.com/questions/4003892/set-the-time-in-alarm-manager-android-alarm-fired-instantly
> where the poster has the same problem as mine.
>
> Someone suggested that
> cal.getTimeInMillis() is returning the current time
> but even in my code this is not the case (in fact my code is the same as the
> original poster).

As the last comment on the accepted answer indicates, that code does
not indicate whether hour and min are zero.

> 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.

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

--
Mark Murphy (a Commons Guy)
http://commonsware.com | http://github.com/commonsguy
http://commonsware.com/blog | http://twitter.com/commonsguy

Warescription: Three Android Books, Plus Updates, One Low Price!

--
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