I'd like to have a notification done weekly from the day it was set. It initializes when it gets called but not the second time.(I fast forwarded the phone clock to see if it would call it but it didn't). It must be the 7*calendar.getTimeInMillis(). How else would I go about having it set for weekly?
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, mHour);
calendar.set(Calendar.MINUTE, mMinute);
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, OnBootReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
//am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 7*calendar.getTimeInMillis(), pendingIntent);
BroadCastReceiver class:
nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence from = "from";
CharSequence message = "message";
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(), 0);
Notification notif = new Notification(icon, tickerText, when);
notif.setLatestEventInfo(context, from, message, contentIntent);
nm.notify(1, notif);
The 7*calendar.getTimeInMillis() is indeed the problem as calendar.getTimeInMillis() returns the time since 1970, so you basically set the repeating to ~42.5 * 7 years from now. You need to set the offset, e.g. 7 (days) * 24 (hours) * 60 (minutes) * 60 (seconds) * 1000 (millies).
After we cleared that - I suggest you avoid using the repeating, and instead set a new alarm each time the invoked code finishes its work, as there are some possible problems with the repeating mechanism.
You don't want the current date * 7 you want:
7 days = 604 800 000 milliseconds
This is how many milliseconds are in 7 days
i.e.
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 604800000L, pendingIntent);
Related
I want to trigger a notification at 8:OO AM daily. Alarm manager is not working from android 9. I tried with work manager also but it's not working.
Currently am using alaram service, its working fine upto andorid 8 version, but not in 9.
Intent intent = new Intent(this, appstartreceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 99, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
long startUpTime = calendar.getTimeInMillis();
// To avoid firing the alarm if the time is passed while setting
if (System.currentTimeMillis() > startUpTime) {
startUpTime = startUpTime + 24 * 60 * 60 * 1000;
}
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, startUpTime, 24 * 60 * 60 * 1000, pendingIntent);
Note : I want to trigger notification even app is killed/closed state.
I'm trying to write code that will run a task on specific hours every day.
I have an hours array that contains integers and I loop through it to set a repeating alarm from that hour and with an interval of a day.
If I just create the service and run the task every 10 seconds or something it does run the AlarmReciever but this code doesn't work after the addition of the Calendar API, what am I doing wrong?
AlarmManager alarmManager;
Calendar current = new GregorianCalendar();
Calendar calendar = new GregorianCalendar();
int[] hours = new int[] {14, 18, 21, 22};
public int onStartCommand(Intent intent, int flags, int startId) {
current.setTimeInMillis(System.currentTimeMillis());
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent1 = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent1, 0);
for (int hour : hours) {
calendar.add(Calendar.DAY_OF_YEAR, current.get(Calendar.DAY_OF_YEAR));
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.DATE, current.get(Calendar.DATE));
calendar.set(Calendar.MONTH, current.get(Calendar.MONTH));
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
return START_STICKY;
}
EDIT: I tried printing out calendar.getTimeInMillis() for every loop and here is the output
I/System.out: 2391249600000
I/System.out: 2643724800000
I/System.out: 2769962400000
I/System.out: 2833038000000
Lets say I take the two first numbers: 2643724800000 - 2391249600000 = 252475200000. 252475200000 / 1000 = 252475200. 252475200 / 60 = 4207920.
I'm pretty sure 4207920 minutes is more than one hour. Why is like this?
Okay, I found out how to fix my problem.
First of all thanks to #MikeL for suggesting to remove calendar.add(Calendar.DAY_OF_YEAR, current.get(Calendar.DAY_OF_YEAR)); because that did fix some stuff, but even after that it didn't work.
To fix the problem I changed PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent1, 0); to PendingIntent pendingIntent = PendingIntent.getBroadcast(this, hour, intent1, 0);
Basically changing the 0 to hour so that every pending intent is different.
User can set their own repeat interval, for example he/she selected 5 minutes to be reminded of the new goal she set. The reminder will start on the goal's start date which is also set by the user.
No problem with setting goal, and setting the repeat interval. The problem is it wont work.
What i would like to happen: This is an example
Goal 1 starts tomorrow. User will get reminder of Goal 1 in every 1 hour tomorrow.
Here's my code:
public void setReminder(){
List<Goals> oneGoal = dbhandler.getLatestGoal(goal_id);
for (final Goals goals : oneGoal) {
if (repeat.isChecked()) {
long futureInMillis = 0;
dbhandler.updateReminders("true",choiceNumber,choiceRepeat,goal_id);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.set(Calendar.DATE,Integer.parseInt(goals.getSDay())); //1-31
cal.set(Calendar.MONTH,Integer.parseInt(goals.getSMonth())-1); //first month is 0!!! January is zero!!!
cal.set(Calendar.YEAR, Integer.parseInt(goals.getSYear()));//year...
//assigned a unique id to notifications
Random random = new Random();
int m = random.nextInt(9999 - 1000) + 1000;
//Create a new PendingIntent and add it to the AlarmManager
Intent intent3 = new Intent(this, TimeAlarm.class);
intent3.putExtra("goalid", Integer.toString(goal_id));
PendingIntent pendingIntent = PendingIntent.getActivity(this,
goals.getGoalId(), intent3, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am =
(AlarmManager) getSystemService(Activity.ALARM_SERVICE);
if (choiceRepeat.equalsIgnoreCase("Seconds")) {
am.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime(), 1000 * choiceNumber,
pendingIntent);
} else if (choiceRepeat.equalsIgnoreCase("Minutes")) {
am.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime(), 1000 * 60 * choiceNumber,
pendingIntent);
} else if (choiceRepeat.equalsIgnoreCase("Hours")) {
am.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime(), 1000 * 60 * 60 * choiceNumber,
pendingIntent);
}
MessageTo.message(SetReminderActivity.this, "You will be reminded every "+choiceNumber+" "+choiceRepeat+" for the new goal.");
//am.cancel(pendingIntent);
}else{
MessageTo.message(SetReminderActivity.this, "You've chosen not to set reminder for the new goal.");
}
}
}
TimeAlarm.java // for the notifications
public class TimeAlarm extends BroadcastReceiver {
NotificationManager nm;
MyDBAdapter dbhandler;
#Override
public void onReceive(Context context, Intent intent) {
int goal_id = Integer.parseInt(intent.getStringExtra("goalid"));
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(), 0);
//assigned a unique id to notifications
Random random = new Random();
int m = random.nextInt(9999 - 1000) + 1000;
List<Goals> oneGoal = dbhandler.getLatestGoal(goal_id);
for (final Goals goals : oneGoal) {
Notification mNotification = new Notification.Builder(context)
.setContentTitle("A Reminder from GSO")
.setContentText(goals.getGoalName())
.setSubText(goals.getStartDate() + " - " + goals.getEndDate())
.setSmallIcon(R.drawable.gsoicon)
.setContentIntent(contentIntent)
.setSound(soundUri)
.build();
nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
// If you want to hide the notification after it was selected, do the code below
mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
nm.notify(m, mNotification);
}
}
}
in Android Manifest:
<receiver android:name=".TimeAlarm" />
I can't tell what wrong with my code. Pls. help.
You are only setting the alarm using AlarmManager's set() method. You should use setRepeating() method for repeating the alarm events.
So, your below line
am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
should be replaced with
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
You can also refer this Example : Create Repeating Alarm .
Example to repeat event on every two minutes
AlarmManager am = (AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),2*60*60,pendingIntent);
You have to declare the receiver in your AndroidManifest.xml
<receiver android:name="TimeAlarm" >
See: http://developer.android.com/guide/topics/manifest/receiver-element.html
In monodroid I want to set an alarm. I would like to have a function I can pass a seconds to and the function creates the alarm at the current time + seconds.
All examples I found were nested in some other projects. I am looking for a general purpose solution.
I found
AlarmManager am = (AlarmManager)getSystemService(alarm);
Intent i= new Intent("MY_INTENT");
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.MINUTE, 2);
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pi);
and changed it to
AlarmManager am = (AlarmManager)GetSystemService(AlarmService);
Intent i = new Intent("MY_INTENT");
PendingIntent pi = PendingIntent.GetBroadcast(this, 0, i, 0);
seconds = Convert.ToInt16(txtMinutes.Text) * 60;
am.Set(AlarmType.ElapsedRealtimeWakeup,SystemClock.ElapsedRealtime() + (seconds * 1000), pi);
But after seconds passed, literally nothing happens.
What to change?
I want to show 2 notifications per day in my application in 2 specific time, until now i'm just able to show one notification.
This is my code, how can i show multiple notification.
one at 7 AM , and the other at 6 PM for example?
Intent myIntent = new Intent(Calender.this, MyAlarmService.class);
int id = (int) System.currentTimeMillis();
pendingIntent = PendingIntent.getService(Calender.this, id,
myIntent, Notification.FLAG_ONLY_ALERT_ONCE);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar timeToSet = Calendar.getInstance();
timeToSet.set(Calendar.HOUR_OF_DAY, hour);
alarmManager.set(AlarmManager.RTC_WAKEUP,
timeToSet.getTimeInMillis(), pendingIntent);
and i called this in MyAlarmService in the onStart method
final Calendar c = Calendar.getInstance();
Notification note = new Notification(R.drawable.icon,
getString(R.string.app_name), System.currentTimeMillis());
Intent intent = new Intent(this, Calender.class);
PendingIntent i = PendingIntent.getActivity(this, 0, intent,
Notification.FLAG_ONGOING_EVENT);
note.setLatestEventInfo(this, getString(R.string.app_name),
"Some String", i);
note.flags |= Notification.FLAG_AUTO_CANCEL;
NOTIFY_ME_ID = System.currentTimeMillis();
mgr.notify((int) NOTIFY_ME_ID, note);
You should set different keys for different notifications. If you use one key for several notifications it will rewrite the same one.