Reputation: 15734
In the below code, it is doing the main thing what I want so far: - Repeats every hour at the same time
Can someone verify if or what I need to do to make sure of the following items?
(1) The alarm will eventually be based on days of a month. As long as it goes off when they wake their phone up (to save battery). It is not hour or minute specific. Only day. How can this be achieved?
(2) If the Activity is destroyed or the phone is rebooted, I am not sure if my AlarmManager stays awake?
(3) Lastly, This code is repeated every time the app starts (thus overwriting any existing AlarmManagers; is this a proper way of doing things, or should I be checking to see if an Alarm exists?
for (int i : AlarmDays) {
if (String.valueOf(i) == null ) {
continue;
}
Calendar cal = Calendar.getInstance();
if (cal.get(Calendar.MINUTE) >= i)
cal.add(Calendar.HOUR, 1);
cal.set(Calendar.MINUTE, i);
Intent intent = new Intent(this, TimeAlarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, i,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
60 * 60 * 1000, pendingIntent);
}
// TimeAlarm.class
public void onReceive(Context context, Intent intent) {
String DebtName = null;
nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence from = "Payment Due";
CharSequence message = "Open App and Update your Balance";
Intent notificationIntent = new Intent(context, ManageDebts.class);
notificationIntent.getExtras();
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
Notification notif = new Notification(R.drawable.icon, "Pay "
+ DebtName + " today!", System.currentTimeMillis());
notif.setLatestEventInfo(context, from, message, contentIntent);
notif.defaults = Notification.DEFAULT_SOUND
| Notification.DEFAULT_LIGHTS;
nm.notify(1, notif);
}
And in my application tag in my manifest:
EDIT:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<Application>
<receiver
android:name=".TimeAlarm"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</Application>
Upvotes: 1
Views: 1313
Reputation: 7672
The AlarmManager will not persist across the phone being rebooted. However, it will persist across the application being killed by the Android scheduler. Because of this, you basically need to:
AlarmManager
to fire.AlarmManager
on boot, by catching the BOOT_COMPLETED
broadcast.Upvotes: 1