Use calendar to set alarm notification android - android

I am trying to get a notification to pop up based on the user date and time they put in. Here is my code for getting the time values
// String GetRawDate Gets The User Value For Date//
String getRawDate = date.getText().toString();
// String SplitDate Splits The Date Into Three Separate Ints//
String[] splitDate = getRawDate.split("/");
// Int GetMonth Gets The Value Of The Month//
int getMonth = Integer.parseInt(splitDate[0]);
// Int GetDay Gets The Value Of The Day//
int getDay = Integer.parseInt(splitDate[1]);
// Int GetYear Gets The Value Of The Year//
int getYear = Integer.parseInt(splitDate[2]);
// Get Military Start Time//
String test = military_start_time;
// Split It//
String[] splitStartTime = test.split(":");
// Get Hour In Integer Form
int getHour = Integer.parseInt(splitStartTime[0]);
// Get Minute In Integer Form//
int getMinute = Integer.parseInt(splitStartTime[1]);
From here I add these values to calendar
// Gets Calendar Instance//
Calendar calendar = Calendar.getInstance();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, getMonth);
cal.set(Calendar.YEAR, getYear);
cal.set(Calendar.DAY_OF_MONTH, getDay);
cal.set(Calendar.HOUR_OF_DAY, getHour);
cal.set(Calendar.MINUTE, getMinute);
Then I set my alarm
// Intent To Start Notification After X Seconds//
Intent alertIntent = new Intent(this, ReminderService.class);
alertIntent.putExtra("name", name.getText().toString());
alertIntent.putExtra("time", starttime.getText().toString());
// Defines Alarm Manager//
AlarmManager alarmManager = (AlarmManager)
getSystemService(Context.ALARM_SERVICE);
// Sets Alarm Manager//
alarmManager.set(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), PendingIntent.getBroadcast(this, 1,
alertIntent, PendingIntent.FLAG_UPDATE_CURRENT));
// Starts Activity ListView//
Intent b = new Intent(this, Reminders.class);
startActivity(b);
overridePendingTransition(R.anim.slid_in, R.anim.slid_out);
Say the user has the date of 6/4/15 and the Time 22:10 I want the notification to show up on this time. For some reason it shows up about 5 seconds after the code is run through. Anybody know what I am doing wrong with the alarm?

try using
alarmManager.setExact(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), PendingIntent.getBroadcast(this, 1,
alertIntent, PendingIntent.FLAG_UPDATE_CURRENT));
P.S: Needs min API:19

Related

how to set multiple alarms using sqlite data?

I am new to android ,here I am developing an alarm app for my working knowledge .
I have completed the following :
creating alarms and storing it into sqlite database.
Fetching all the alarms which has the status as active .
I have tried many stackoverflow post and their solutions and other blog posts which related to my doubt but I can't get a solution for my problem .
What is my problem is I am receiving number of alarm timings from sqlite database which I have set it before and I want to set all the alarms on the stored time .
Here I don't know how to set it .
Can anyone help me to set the multiple alarms .
I am really looking for someone's help to learn and experience these things please help me .
Thanks.
You need Alarm Manager and Pending Intent more.
for (int i = 0; i < ActivemyAlarms.size(); i++) {
int mHour = 0,mMin=0;
String amPm = null;
int mAlarmId = ActivemyAlarms.get(i).getALARM_ID(); //each alarm has an unique Id ,for differentiate one from another
String mAlarmTime = ActivemyAlarms.get(i).getALARM_TIME(); // alarm time (11:12:AM)
if (!(mAlarmTime == null)) {
String mtime = mAlarmTime; // alarm time format is 12hr format (ex : 11:12:AM)
String[] time = mtime.split(":");
mHour = Integer.parseInt(time[0].trim()); // get 11 hour
mMin = Integer.parseInt(time[1].trim()); // get 12 min
amPm = ((time[2].trim()));
}
Calendar calendar = Calendar.getInstance();
calendar.set(calendar.HOUR_OF_DAY, amPm!=null && amPm.equalsIgnoreCase("pm")?(mHour+12):mHour);
calendar.set(calendar.MINUTE, mMin);
calendar.set(calendar.SECOND, 0);
calendar.set(calendar.MILLISECOND, 0);
Intent intent = new Intent(this,AlarmReceiver.class); //calling my Alarm service class which plays a music on the specific time
final int _id = (int) System.currentTimeMillis(); // get calendar instance
//Use Alarm manager and Pending Intent
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, mAlarmId, intent, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);
}
And to cancel any Alarm call alarmManager.cancel(PendingIntent) like;
Intent intent = new Intent(this,AlarmReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, mAlarmId, intent, 0);
alarmManager.cancel(alarmIntent);

Setting up multiple alarms in Android

When I make an alarm with the time picker the new one always overrides the previous one. I need help to make multiple alarms that override each other. I am using the following code:
Intent i = new Intent("class");
PendingIntent operation = PendingIntent.getActivity(getBaseContext(), 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);
AlarmManager alarmManager = (AlarmManager) getBaseContext().getSystemService(ALARM_SERVICE);
DatePicker dpDate = (DatePicker) findViewById(R.id.dp_date);
TimePicker tpTime = (TimePicker) findViewById(R.id.tp_time);
int year = dpDate.getYear();
int month = dpDate.getMonth();
int day = dpDate.getDayOfMonth();
int hour = tpTime.getCurrentHour();
int minute = tpTime.getCurrentMinute();
GregorianCalendar calendar = new GregorianCalendar(year, month, day, hour, minute);
long alarm_time = calendar.getTimeInMillis();
alarmManager.set(AlarmManager.RTC_WAKEUP, alarm_time, operation);
Toast.makeText(getBaseContext(), "Alarm is set successfully",Toast.LENGTH_SHORT).show();

android: am pm format of alarm

I am using the alarmmanger class set method for setting the alarm. i
takes the input from user through timepicker dialog for setting the
alarm.alarm work fine when i set specific hour and minutes but
application is not following the am/pm logic. mean if i set the alarm
10:31 am while in system time is 10:30 pm then alarm invoke at 10:31 pm not at 10:30 am.anyone tell me whats the reason?
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR, hourOfDay);
time.set(Calendar.MINUTE, minute);
time.set(Calendar.SECOND, 5);
//time.set(Calendar.AM_PM);
AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
alarmMgr.set(AlarmManager.RTC_WAKEUP,time.getTimeInMillis(), pendingIntent);
you need to set the time with the time format using SimpleDateFormat or DateFormat class which will give the date based on the date-time string and get that value using getTime and set into the alarm in set method.
Or you can do another way get the alarm time and check whether it's am or pm and set this attribute into the calendar object with time and date and get millisecond value from the calendar set into the alarm.set() method.
Hope you get some idea/suggestion
Edit
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a"); // this is you format
Date d = sdf.parse("19/12/2011 03:47:00 pm"); // this string getting you from your timepicker
Intent myIntent = new Intent(youractivity.this, AlarmService.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(youractivity.this, 0, myIntent, PendingIntent.FLAG_ONE_SHOT);
am.set(AlarmManager.RTC_WAKEUP, d.getTime(), pendingIntent);
Note: you need to put into the try and catch block parse part it may be cause error during parsing time
I used this method in setting alarm:
/**
* Set the Alarm
*
* #param context the activity context
* #param id the alarm ID for this app
* #param hour the alarm hour
* #param minute the alarm minute
* #param timeZone the timezone am = Calendar.AM or pm = Calendar.PM
*/
public static void setAlarm(Context context, int id, int hour, int minute, int timeZone) {
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.AM_PM, timeZone);
Intent intent = new Intent(context, PopupActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, id, intent, 0);
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 10, pIntent);
}
For the timezone parameter use either am = Calendar.AM or pm = Calendar.PM
Change the below line:
time.set(Calendar.HOUR, hourOfDay);
to
time.set(Calendar.HOUR_OF_DAY, hourOfDay);

Alarm Manager fails to Trigger Alarm if date is added to calender

I am trying to create the Alarms in my application using AlarmManager.
I am able to set multiple alarms, but if DATE parameter is added to Calender, the alarms are not at all triggered. Following is my code
Intent intent = new Intent(this, OneShotAlarm.class);
/*Pass the task row ID as the Unique ID for Pending Intent*/
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), (int) rowid , intent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault());
calendar.clear();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, mHour);
calendar.set(Calendar.MINUTE, mMinute);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
long timeSet = calendar.getTimeInMillis();
alarmManager.set(AlarmManager.RTC_WAKEUP, timeSet, pendingIntent);
If I add the Date parameters to Calender as
calendar.add(Calendar.DAY_OF_MONTH, mDay);
calendar.add(Calendar.MONTH, mMonth);
calendar.add(Calendar.YEAR, mYear);
The alarms are not triggered. I have to schedule a event at a future date. Please suggest what I am missing. Thanks for the help!!
P.S. I am taking the date and time from Date & Time dialog picker
I have implement AlarmManager many times, Following technique will help you.
calculate your alarm time in milliseconds for example you want to set alarm after 10 minutes then 10*60*1000 millisecond after current time.
Add your calculated time in current millisecond
Example
long currentTime = System.currentTimeMillis();
long fireTime = 10 * 60 * 1000;
Intent ucintent = new Intent(getApplicationContext(),TimeAlarmReceiver.class);
ucintent.putExtra("isAlarm", true);
PendingIntent mTimeSlot = PendingIntent.getBroadcast(getApplicationContext(), (int)fireTime , ucintent, PendingIntent.FLAG_ONE_SHOT);
alarmManager.set(AlarmManager.RTC_WAKEUP,currentTime+ fireTime, mTimeSlot);
Above example works perfect.
Thank You,
Ketan's answer is good but there is an error.
long currentTime = System.currentTimeMillis();
long fireTime = 10 * 60 * 1000;
Intent ucintent = new Intent(getApplicationContext(),TimeAlarmReceiver.class);
ucintent.putExtra("isAlarm", true);
PendingIntent mTimeSlot = PendingIntent.getBroadcast(getApplicationContext(), (int) requestCode, ucintent, PendingIntent.FLAG_ONE_SHOT);
alarmManager.set(AlarmManager.RTC_WAKEUP,currentTime+ fireTime, mTimeSlot);
However you don't want "fireTime" in the PendingIntent. You should have a request code. Which is a code you create to identify your pending intents. It works in Ketan's case because he is always using the same time. But if you change the time, you will end up with two different intents.
see https://developer.android.com/reference/android/app/PendingIntent.html

AlarmManager setting more than once?

I am using this code to set a Alarm everyday for 8 oclock the next day.
I am setting this alarm in an activity that can be opened based upon the user.
//Setting alarm to fire off NEW_GAME intent every 24 hours.
String alarm = Context.ALARM_SERVICE;
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND,0);
calendar.set(Calendar.MILLISECOND, 0);
Log.i("Test", "Current time: " + System.currentTimeMillis() );
Log.i("Test", "Calendar time: " + calendar.getTimeInMillis() );
int currentDate = calendar.get(Calendar.DATE);
calendar.set(Calendar.DATE, currentDate+1);
Log.i("Test", "Calendar time with a day added: " + calendar.getTimeInMillis() );
AlarmManager am = (AlarmManager)getActivity().getSystemService(alarm);
Intent intent = new Intent("NEW_ITEM");
PendingIntent sender = PendingIntent.getBroadcast(getActivity(), 0, intent, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis() , AlarmManager.INTERVAL_DAY, sender);
My only question is..Lets say at 10:00 o clock today am. i open the activity that alarm is set for tomorrow..Lets say i open the activity again at 12:00 am mid-night, will the alarm set earlier that day be overr written by the current alarm being set?
If you use the same request number (second parameter) while creating the PendingIntent object
PendingIntent sender = PendingIntent.getBroadcast(getActivity(), 0, intent, 0);
then it will overwrite the current PendingIntent and hence will replace the current Alarm.
It will also depend on what you pass as the last parameter to it. Possible values given in the constants section here.

Categories

Resources