每次app运行时,警报管理器都会触发

时间:2015-11-29 09:10:46

标签: android notifications alarmmanager repeatingalarm

我想从AlarmManager创建一个重复闹钟,每天21:00触发,以显示通知。所以我创建了一个服务,并在清单中声明,在服务类中,我编写了一个计划重复警报的方法。

public static void setRecurringAlarm(Context context) {

    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(context, NotificationService.class);
    PendingIntent pi = PendingIntent.getService(context, 0, i, 0);
    am.cancel(pi);

    Calendar updateTime = Calendar.getInstance();
    updateTime.setTimeZone(TimeZone.getDefault());
    updateTime.set(Calendar.HOUR_OF_DAY, 21);
    updateTime.set(Calendar.MINUTE, 00);
    updateTime.set(Calendar.SECOND, 00);

    am.setInexactRepeating(AlarmManager.RTC_WAKEUP,
            updateTime.getTimeInMillis(),
            AlarmManager.INTERVAL_FIFTEEN_MINUTES, pi);

}

(对于测试我设置延迟INTERVAL_FIFTEEN_MINUTES)。

我在我的启动画面活动的onResume()和设置为接收BOOT_COMPLETED的BroadcastReceiver中调用此方法。

@Override 
protected void onResume() {
    super.onResume();
    NotificationService.setRecurringAlarm(this);
}

这是我的BroadcastReceicer:

public class NotificationBootReceiver extends BroadcastReceiver {

    public void onReceive(Context context, Intent intent) {
        NotificationService.setRecurringAlarm(context);
    }

}

这是我的清单:

    <receiver android:name=".notification.NotificationBootReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
        <service android:name=".notification.NotificationService" />
    </application>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

问题是我每次打开应用程序并启动启动警报时触发警报并显示通知。

0 个答案:

没有答案