I want to be able to create an alarm to ring a notification to the user to start the application every 2 minutes. Everything works fine, but the notification appears when i start my application manually. Here are my code :
Receiver:
public void onReceive(Context context, Intent intent) {
nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence from = "myactivity";
CharSequence message = "click to start activity";
Intent scheduledIntent = new Intent(context, AmslerTestActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
scheduledIntent, 0);
Notification notif = new Notification(R.drawable.icon,
message, System.currentTimeMillis());
notif.setLatestEventInfo(context, from, message, contentIntent);
notif.flags = Notification.FLAG_AUTO_CANCEL;
notif.defaults |= Notification.DEFAULT_SOUND;
nm.notify(1, notif);
scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(scheduledIntent);
}
Scheduler:
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, 01);
cal.set(Calendar.SECOND, 0);
Intent intent = new Intent(myactivity.this, AlarmReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
// Get the AlarmManager service
am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 2 * 60 * 1000, sender);
I want the notification to only ring when the code is not running.
Put the “scheduler” part of your code in
onPause,onStoporonDestroyin order to set the alarm only once yourActivitystops. Read here to decide which is best for your purposes. Then, when doingam.setRepeating, useSystem.currentTimeMillis() + 2 * 60 * 1000for thetriggerAtTimeto make the alarm trigger 2 min from the time theActivitystops. Then it will repeat every 2 min based on the 3rd parameter, theinterval, which you currently have set correctly to 2 min.