警报管理器触发的待定意图似乎立即触发 [英] Pending Intent triggered by Alarm Manager seems to fire right away

查看:109
本文介绍了警报管理器触发的待定意图似乎立即触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设置了一个警报管理器,该警报管理器应该在一天中的某个特定时间触发待处理的意图.

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

我将代码放在Main Activity的onCreate()方法中,因为我认为这是放置代码的最佳位置?

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

下面是代码:

    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.

什么原因导致Intent立即触发?而我该如何阻止它呢?

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

推荐答案

您的问题在这里:

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()将返回当前时间戳(System.currentTimeMillis())之前的时间戳,这就是Alarm立即触发的原因.

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

要解决您的问题,

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
}

如果您始终想在1天后的凌晨4点开始闹钟.您可以删除条件并执行以下操作:

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

这篇关于警报管理器触发的待定意图似乎立即触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆