So I'm trying to make an AlarmManager that's suppose to launch at a specific time. The problem is that when I set the time, tt doesn't work. I think the main problem is that after I have change the time on Calendar, in logs object value "time" shows ?
timeOff = Calendar.getInstance();
System.out.println(timeOff);
timeOff.add(Calendar.DAY_OF_WEEK,Calendar.FRIDAY);
timeOff.set(Calendar.HOUR_OF_DAY, 16);
timeOff.set(Calendar.MINUTE, 30);
timeOff.set(Calendar.SECOND, 0);
System.out.println(timeOff);
System.out.println("TIME:: "+timeOff.getTimeInMillis());
Intent intent = new Intent(TabsActivity.this, Receiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(TabsActivity.this, 1122, intent, 0);
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.setRepeating(am.RTC_WAKEUP, timeOff.getTimeInMillis(),timeOff.getTimeInMillis()+ 1000,pendingIntent);// + 604800000L,pendingIntent);
Logs shows this:
Before change:
java.util.GregorianCalendar[time=1406899765159,areFieldsSet=true,lenient=true,zone=Europe/Riga,firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2014,MONTH=7,WEEK_OF_YEAR=31,WEEK_OF_MONTH=1,DAY_OF_MONTH=1,DAY_OF_YEAR=213,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=1,AM_PM=1,HOUR=4,HOUR_OF_DAY=16,MINUTE=29,SECOND=25,MILLISECOND=159,ZONE_OFFSET=7200000,DST_OFFSET=3600000]
After Change:
java.util.GregorianCalendar[time=?,areFieldsSet=false,lenient=true,zone=Europe/Riga,firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2014,MONTH=7,WEEK_OF_YEAR=32,WEEK_OF_MONTH=2,DAY_OF_MONTH=7,DAY_OF_YEAR=219,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=1,AM_PM=1,HOUR=4,HOUR_OF_DAY=16,MINUTE=30,SECOND=0,MILLISECOND=159,ZONE_OFFSET=7200000,DST_OFFSET=3600000]
As you see the value -
Time=?
So my question, what am I doing wrong, why does after I have set the time, it doesn't show. And even if I try to log out plain timeOff.getTimeInMillis() , it doesn't show anything at all.
Solution
Change timeOff.add(Calendar.DAY_OF_WEEK,Calendar.FRIDAY) to timeOff.set(Calendar.DAY_OF_WEEK,Calendar.FRIDAY)
since calendar.add() method is abstract , you can use like this
Calendar timeOff = Calendar.getInstance();
System.out.println(timeOff);
timeOff.add(Calendar.DAY_OF_WEEK,Calendar.FRIDAY);
timeOff.getTime()
//System.out.println(timeOff.getTime());
timeOff.set(Calendar.HOUR_OF_DAY, 16);
timeOff.set(Calendar.MINUTE, 30);
timeOff.set(Calendar.SECOND, 0);
System.out.println(timeOff);
System.out.println("TIME:: "+timeOff.getTimeInMillis());
Related
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);
I want to trigger repeating alarm at specific time & I'm using below code but it does not trigger the alarm at the time I wanted.
boolean weeklyAlarmUp = (PendingIntent.getBroadcast(ctxt, 0, new Intent(ctxt, ScheduledWeeklyService.class), PendingIntent.FLAG_NO_CREATE) != null);
if (!weeklyAlarmUp) {
AlarmManager mgr = (AlarmManager)ctxt.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(ctxt, ScheduledWeeklyService.class);
PendingIntent pi = PendingIntent.getBroadcast(ctxt, 0, i, 0);
Date date = null;
try {
date = (Date) formatter.parse("17-Mar-2014 13:10:00"); // This date & time will be an user input from some activity
} catch (ParseException e) {
e.printStackTrace();
}
long triggerWeeklyTaskAt = date.getTime();
long currentTime = System.currentTimeMillis();
// Don't trigger the alarm is input date time is in the past, set it to next day but at the same time
if (currentTime > triggerWeeklyTaskAt) {
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 13);
c.set(Calendar.MINUTE,10);
c.set(Calendar.SECOND,0);
c.set(Calendar.MILLISECOND, 0);
c.add(Calendar.DATE, 1);
date = c.getTime();
triggerWeeklyTaskAt = date.getTime();
}
Locale locale = Locale.getDefault();
msgFormatter.setLocale(locale);
Object[] objs = { "Dummy" };
SchedulerLog.logInfo(ctxt, ctxt.getString(R.string.module_scheduler), msgFormatter.format(objs));
mgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, triggerWeeklyTaskAt, PERIOD_WEEKLY, pi);
}
Can anyone tell me what is wrong in below code? How can I check what time it'll trigger alarm at?
Thanks
Your outer if statement looks a bit weird. Are you sure execution is making it inside of it? Throw in a Log statement and/or step through the code to make sure.
If I understand your logic, you're attempting to not create a duplicate PendingIntent. So if the PI already exists, you bypass the whole body of the if. The problem with that is that your alarm setup is inside the if statement too.
The reference page says "...even if its owning application's process is killed, the PendingIntent itself will remain usable from other processes that have been given it." So perhaps a matching PI still exists from a previous run? It might be better to always (re)create the PI, but use FLAG_CANCEL_CURRENT or FLAG_UPDATE_CURRENT depending on whether you want to update the particulars.
m taking time from time picker and when i set scheduling time to do work, it creating problem
SharedPreferences prefs = getSharedPreferences("CONSTANT_FILE_NAME",Context.MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor= prefs.edit();
editor.putLong("timepickerhour", timePicker.getCurrentHour());
editor.putLong("timepickerminute", timePicker.getCurrentMinute());
editor.putLong("milis", milis);
editor.commit();
SharedPreferences prfs = getSharedPreferences("CONSTANT_FILE_NAME",Context.MODE_PRIVATE);
h =prfs.getLong("timepickerhour",0);
m =prfs.getLong("timepickerminute",0);
r =prfs.getLong("milis",0);
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent1 = new Intent(Scheduling.this, Feedback.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(Scheduling.this, 0,
intent1, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar1 = Calendar.getInstance();
calendar1.set(Calendar.HOUR_OF_DAY, (int) h);
calendar1.set(Calendar.MINUTE, (int) m);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP,calendar1.getTimeInMillis(),
r, pendingIntent);
m facing problem when i give past time then now, as like now time is 4:25 pm if i set time 2:25 pm then that scheduling task run on the spot......
also problem if now time is 4:38 pm and i set time 4:38 am then also run code also now
plz help me
thnks in advance
same problem like this
How can i invoke the alarm for the past time using alarm manager in android?
if (calendar1.before(cal_now)) {// if its in the past increment
calendar1.add(Calendar.DATE, 1);
}
just add this line I think You will get right time:---
Calendar calendar1 = Calendar.getInstance();
calendar1.setTimeInMillis(System.currentTimeMillis());
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
I am using this code to launch an Alarm.
The alarm is set in an Activity that the user can launch.
//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);
I was told i need to supply a uniqu id so that the alarm doesnt over writte each other where getBroadcast() is.
The problem is how do I do this when the user can open the Activity as many times as they want?
Also if I supply a unique ID each time this means it could possibly set 5 of the same ALARMS because of the unique id's.
How or what is the best way to get around this?
you could always just use the unix timestamp of your target time as the unique id. that way, alarms for the exact time WILL override each other, while all other alarms will stay seperate
[EDIT:] Here is some example code:
AlarmManager am = (AlarmManager)getActivity().getSystemService(alarm);
Intent intent = new Intent(String.valueOf(calendar.getTimeInMillis()));
PendingIntent sender = PendingIntent.getBroadcast(getActivity(), 0, intent, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis() , AlarmManager.INTERVAL_DAY, sender);