Alarm manager trigger every time app running

假如想象 提交于 2020-01-15 03:21:25

问题


I want to create a repeating alarm from AlarmManager which is triggered at 21:00 every day to show a notification. So i create a service and declare that in manifest, in the service class i wrote a method for schedule repeating alarms.

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

}

(For test i set the delay INTERVAL_FIFTEEN_MINUTES).

I call this method at onResume() of my splash screen activity and in a BroadcastReceiver that is set up to receive BOOT_COMPLETED.

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

this is my BroadcastReceicer :

public class NotificationBootReceiver extends BroadcastReceiver {

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

}

and this is my manifest :

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

the problem is every time i open the app and splashscreen running the alarm triggered and notification will be shown.

来源:https://stackoverflow.com/questions/33981142/alarm-manager-trigger-every-time-app-running

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!