简体   繁体   中英

Pending Intent triggered by Alarm Manager seems to fire right away

I have set up an Alarm Manager that is supposed to trigger a Pending Intent at a certain time of day.

I placed the code in the onCreate() method of my Main Activity, as I believed this was the best place to put it?

Below is the code:

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 4); // trigger at 4am in the morning
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);

    final Intent updateIntent = new Intent(Intent.ACTION_MAIN, null);
    updateIntent.addCategory(Intent.CATEGORY_HOME);
    final ComponentName cn = new ComponentName(
            "com.example.myotherapp",
            "com.example.myotherapp.MainActivity");
    updateIntent.setComponent(cn);
    updateIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(), 0, updateIntent, 0);

    AlarmManager alarm = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    alarm.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pIntent); // launch at 4am, then every day (24 hours)

The Alarm Manager works, I can see it fire at the specified time, but it also seems that the Pending Intent is fired as soon as this base app starts.

What is causing the Intent to fire right away? And how can I stop it from doing so?

Your problem is here:

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 4); // trigger at 4am in the morning
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);

calendar.getTimeInMillis() will return the timestamp that BEFORE current timestamp (System.currentTimeMillis()) so that is why Alarm fire right away.

To fix your problem:

long triggerTime = calendar.getTimeInMillis();
if (triggerTime  <= System.currentTimeMillis() + 3000) 
{
    // 3 Second distance

   calendar.add(Calendar.DATE, 1);  // Add 1 day --> Trigger 1 day later from now
}

IF you always want to start your alarm at 4am 1 day later. You can remove condition and doing like this:

calendar.add(Calendar.DATE, 1); // Add 1 day --> Calendar time will be tomorrow 4am

AND

alarm.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pIntent);

You set the alarm to trigger at 4 am today, not tomorrow. Because that time has already passed, the alarm triggers immediatelly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM