Reputation: 402
i have a notification with a broadcast service and i have defined my notification in my main activity's oncreate but the problem is the notification fires again and again each time i open main activity. it is supposed to fire only according to the set time.
// Fire Notification from ReceiverReminder
Intent intent = new Intent(this, ReceiverReminder.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager) this
.getSystemService(Context.ALARM_SERVICE);
long recurring = (1 * 60000 * 60 * 24); // in milliseconds
am.setRepeating(AlarmManager.RTC, Calendar.getInstance()
.getTimeInMillis(), recurring, sender);
//
Upvotes: 0
Views: 642
Reputation: 4766
Read the description of setRepeating method in developer.android.com
According to it the parameters are:
- type - One of ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC, or RTC_WAKEUP.
- triggerAtMillis - time in milliseconds that the alarm should first go off, using the appropriate clock (depending on the alarm type).
- intervalMillis - interval in milliseconds between subsequent repeats of the alarm.
- operation - Action to perform when the alarm goes off; typically comes from IntentSender.getBroadcast().
Now you are passing the current time as the second parameter, telling it to fire immediately, and then repeat itself every 1 * 60000 * 60 * 24 millis.
If you want the alarm to fire for the first time after 1 * 60000 * 60 * 24 millis, the change your method to:
am.setRepeating(AlarmManager.RTC, Calendar.getInstance()
.getTimeInMillis() + recurring, recurring, sender);
Edit:
Based on your comments, you shouldn't reset the alarm every time the activity is opened. So you should save your state somewhere, for example in a variable in SharedPreferences. So your code should insted be somewhat like this:
boolean areAlarmsAlreadySet = ...// get boolean variable from SharedPreferences
if (!areAlarmsAlreadySet)
{
Intent intent = new Intent(this, ReceiverReminder.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager) this
.getSystemService(Context.ALARM_SERVICE);
long recurring = (1 * 60000 * 60 * 24); // in milliseconds
am.setRepeating(AlarmManager.RTC, Calendar.getInstance()
.getTimeInMillis() + recurring, recurring, sender);
// set the variable in SharedPreferences to true
}
Upvotes: 2
Reputation: 152
PendingIntent alarmIntent = PendingIntent.getBroadcast(this.getContext(), 0, intent, 0);
//After after 30 seconds
alarmManager2.setRepeating(AlarmManager.RTC_WAKEUP, twopm.getTimeInMillis(), 30*1000 , alarmIntent);
And
AndroidManifest.xml
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
Upvotes: 0