Alarm service Not stopping or starts improper - android

i m really fed up with the alarm service that i m created. i created an alarm service for showing an alert in my application at 8 am, 4 pm , 12 am of each day in my application. It works fine and alert showing perfectly. i'm canceling my service when closing the app, but some times the alert comes without meeting the time such as after exit the app, when removing the app from tab history, when takes the settings of the device, i'm not getting why this happens, i was checking for a solution in SO but didnt get any proper solution please help me
here giving my code.
public void StartService()
{
Calendar c = Calendar.getInstance();
dfcurrent = new SimpleDateFormat("dd MMM yyyy");
long currentTime = System.currentTimeMillis();
currentdate = new Date(System.currentTimeMillis());
String currentdate1 = dfcurrent.format(currentdate);
Long datetoalert1 = Utility.DateReturn(currentdate1+" - "+08:00AM);
if(datetoalert1 < currentTime)
{
Date d = new Date(datetoalert1);
c.setTime(d);
c.add(Calendar.DATE, 1);
d = c.getTime();
datetoalert1 = d.getTime();
}
Long datetoalert2 = Utility.DateReturn(currentdate1+" - "+04:00PM);
if(datetoalert2 < currentTime)
{
Date d = new Date(datetoalert2);
c.setTime(d);
c.add(Calendar.DATE, 1);
d = c.getTime();
datetoalert2 = d.getTime();
}
Long datetoalert3 = Utility.DateReturn(currentdate1+" - "+00:00AM);
if(datetoalert3 < currentTime)
{
Date d = new Date(datetoalert3);
c.setTime(d);
c.add(Calendar.DATE, 1);
d = c.getTime();
datetoalert3 = d.getTime();
}
Intent myIntent1 = new Intent(Login.this, MyReceiver.class);
pendingIntentSApp1 = PendingIntent.getBroadcast(Login.this, 7, myIntent1,0);
pendingIntentSApp2 = PendingIntent.getBroadcast(Login.this, 8, myIntent1,0);
pendingIntentSApp3 = PendingIntent.getBroadcast(Login.this, 9, myIntent1,0);
AlarmManager alarmManager1 = (AlarmManager)getSystemService(ALARM_SERVICE);
AlarmManager alarmManager2 = (AlarmManager)getSystemService(ALARM_SERVICE);
AlarmManager alarmManager3 = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager1.set(AlarmManager.RTC, datetoalert1, pendingIntentSApp1);
alarmManager2.set(AlarmManager.RTC, datetoalert2, pendingIntentSApp2);
alarmManager3.set(AlarmManager.RTC, datetoalert3, pendingIntentSApp3);
}
i m cancelling this pending intent when closing the app. here giving the code
public void exit_btn_click(View view)
{
Intent myIntent1 = new Intent(Login.this, MyReceiver.class);
pendingIntentSApp1 = PendingIntent.getBroadcast(Login.this, 7, myIntent1,0);
pendingIntentSApp2 = PendingIntent.getBroadcast(Login.this, 8, myIntent1,0);
pendingIntentSApp3 = PendingIntent.getBroadcast(Login.this, 9, myIntent1,0);
AlarmManager alarmManager1 = (AlarmManager)getSystemService(ALARM_SERVICE);
AlarmManager alarmManager2 = (AlarmManager)getSystemService(ALARM_SERVICE);
AlarmManager alarmManager3 = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager1.cancel(pendingIntentSApp1);
alarmManager2.cancel(pendingIntentSApp2);
alarmManager3.cancel(pendingIntentSApp3);
System.exit(0);
}

first of all you should not do this:
AlarmManager alarmManager1 = (AlarmManager)getSystemService(ALARM_SERVICE);
AlarmManager alarmManager2 = (AlarmManager)getSystemService(ALARM_SERVICE);
AlarmManager alarmManager3 = (AlarmManager)getSystemService(ALARM_SERVICE);
enough only one link to alarmManager.
Also try to remove
System.exit(0);
call

try to add flag to the pending intent
pendingIntentSApp1 = PendingIntent.getBroadcast(Login.this, 7, myIntent1,PendingIntent.FLAG_UPDATE_CURRENT);
or better alarm id

You will have to cancel the PendingIntent as well after you cancel the alarm.
try {
alarmManagerstop.cancel(getSendLocationIntent(context, 0));
getSendLocationIntent(context, 0).cancel();
} catch (Exception e) {
e.printStackTrace();
}
This will fix your problem.

Related

Dialy Alarm code Explanation

I am new to android , I want to make alarm that notify me dialy at 11am .I have found some code on net,But dont know some part of it. Below is code
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(AndroidAlarmService.this, MyAlarmService.class);
pendingIntent = PendingIntent.getService(AndroidAlarmService.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis()); does
calendar.add(Calendar.SECOND, 10);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 5*1000, pendingIntent);
Toast.makeText(AndroidAlarmService.this, "Start Alarm", Toast.LENGTH_LONG).show();
}});
can any one explain me what this two line does
calendar.setTimeInMillis(System.currentTimeMillis()); does
calendar.add(Calendar.SECOND, 10);
And also help me how can i set alarm that will notify me on the same time for example at 11am
Call this function where you need:
private void setDailyNotification(int ID, int hh, int mm, int ss) {
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent alarmIntent = new Intent(Dashboard.this, MyDailyReceiver.class);
alarmIntent.putExtra("ID", ID);
Log.d("setDailyNotification", "ID:" + ID);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
Dashboard.this, ID, alarmIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
mEverydayPendingIntent = pendingIntent;
Calendar calendar = Calendar.getInstance();
Calendar now = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hh);
calendar.set(Calendar.MINUTE, mm);
calendar.set(Calendar.SECOND, ss);
// check whether the time is earlier than current time. If so, set it to
// tomorrow. Otherwise, all alarms for earlier time will fire
if (calendar.before(now)) {
calendar.add(Calendar.DATE, 1);
}
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
mEverydayPendingIntent);
Log.d("setRepeated", "ID:" + ID);
}
Broadcast receiver:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
context);
mBuilder.setContentTitle("Daily Summery");
mBuilder.setContentText("Today's Transaction");
mBuilder.setSmallIcon(R.drawable.app_icon);
Log.d("tag1234", "In if" + daily_Reminder);
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
mBuilder.setStyle(inboxStyle);
mNotificationMa = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationMa.notify(11, mBuilder.build());
call function like this:
setDailyNotification(11, 11,00, 00);
System.currentTimeMillis()- gets the current time from the device.
calendar.setTimeInMillis()- sets the current time.
calendar.add(Calendar.SECOND, 10) - adds ten seconds to the current time.
In total, you are fetching the current time of the device and adding ten seconds in it.
You can try this Worked for me
int interval = 1000 * 60 * 1;
// 1 for minutes ,you can pass 60*24
//And set alarm manager like this
Intent alarmIntent = new Intent(AlaramManagerActivity.this, NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(AlaramManagerActivity.this, RQS_1, alarmIntent, 0);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),interval, pendingIntent);
Intent myIntent = new Intent(activity.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(Splash.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar firingCal= Calendar.getInstance();
Calendar currentCal = Calendar.getInstance();
firingCal.set(Calendar.HOUR,11); // At the hour you wanna fire
firingCal.set(Calendar.MINUTE, 0); // Particular minute
firingCal.set(Calendar.SECOND, 0); // particular second
long intendedTime = firingCal.getTimeInMillis();
long currentTime = currentCal.getTimeInMillis();
if(intendedTime >= currentTime){
// you can add buffer time too here to ignore some small differences in milliseconds
// set from today
alarmManager.setRepeating(AlarmManager.RTC, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent);
}
else{
// set from next day
// you might consider using calendar.add() for adding one day to the current day
firingCal.add(Calendar.DAY_OF_MONTH, 1);
intendedTime = firingCal.getTimeInMillis();
alarmManager.setRepeating(AlarmManager.RTC, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent);}

application start at a specific time using AlarmManager [duplicate]

I have searched a lot of places but couldnt find a clean sequential explanation of how to start a service (or if thats not possible then an activity) at a specific time daily using the AlarmManager??
I want to register several such alarms and triggering them should result in a service to be started. I'll be having a small piece of code in the service which can then execute and i can finish the service for good....
Calendar cal = Calendar.getInstance();
Calendar cur_cal = Calendar.getInstance();
cur_cal.setTimeInMillis(System.currentTimeMillis());
Date date = new Date(cur_cal.get(Calendar.YEAR), cur_cal.get(Calendar.MONTH), cur_cal.get(Calendar.DATE), 16, 45);
cal.setTime(date);
Intent intent = new Intent(ProfileList.this, ActivateOnTime.class);
intent.putExtra("profile_id", 2);
PendingIntent pintent = PendingIntent.getService(ProfileList.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pintent);
System.out.println("The alarm set!!");
i tried this code to activate the alarm at 4.45... but its not firing the service... do i have to keep the process running??
M i doing anything wrong???
One more thing, my service gets perfectly executed in case i use the following code:
long firstTime = SystemClock.elapsedRealtime();
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 30*1000,pintent);
HI friends,
After a lot of researching and with reference from "Pentium10"'s question on the same topic i managed to get it working. Though i still cant understand why the "date" concept and the Calendar(non GregorianCalendar) object which i have mentioned in the question are not working correctly.
Calendar cur_cal = new GregorianCalendar();
cur_cal.setTimeInMillis(System.currentTimeMillis());//set the current time and date for this calendar
Calendar cal = new GregorianCalendar();
cal.add(Calendar.DAY_OF_YEAR, cur_cal.get(Calendar.DAY_OF_YEAR));
cal.set(Calendar.HOUR_OF_DAY, 18);
cal.set(Calendar.MINUTE, 32);
cal.set(Calendar.SECOND, cur_cal.get(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cur_cal.get(Calendar.MILLISECOND));
cal.set(Calendar.DATE, cur_cal.get(Calendar.DATE));
cal.set(Calendar.MONTH, cur_cal.get(Calendar.MONTH));
Intent intent = new Intent(ProfileList.this, IntentBroadcastedReceiver.class);
PendingIntent pintent = PendingIntent.getService(ProfileList.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);
//Create alarm manager
AlarmManager alarmMgr0 = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
//Create pending intent & register it to your alarm notifier class
Intent intent0 = new Intent(this, AlarmReciever.class);
PendingIntent pendingIntent0 = PendingIntent.getBroadcast(this, 0, intent0, 0);
//set timer you want alarm to work (here I have set it to 7.20pm)
Intent intent0 = new Intent(this, OldEntryRemover.class);
Calendar timeOff9 = Calendar.getInstance();
timeOff9.set(Calendar.HOUR_OF_DAY, 19);
timeOff9.set(Calendar.MINUTE, 20);
timeOff9.set(Calendar.SECOND, 0);
//set that timer as a RTC Wakeup to alarm manager object
alarmMgr0.set(AlarmManager.RTC_WAKEUP, timeOff0.getTimeInMillis(), pendingIntent0);
Then in your AlarmReciever class which is a broadcastReciever, under onRecieve method put your logic. This will take care of what ever the logic you want to handle when the time comes to 7.20 pm.
If you need to set multiple alarms, create another Calendar instance & set time values appropriately. You also need to create another instance for pendingIntent otherwise timers will overlap. Then set it to same alarmManager with new timer & pendingIntent.
You can read document from https://developer.android.com/training/scheduling/alarms.html
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
// Set the alarm to start at 8:30 a.m.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 30);
// setRepeating() lets you specify a precise custom interval--in this case,
// 20 minutes.
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
1000 * 60 * 20, alarmIntent);
The following code should work fine and it starts the service # 7:40 PM every day. Also, if device shuts down then all your alarms get cancelled.
Make sure to set up all the alarms after BOOT is completed.
Intent slIntent = new Intent(this, x.class);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 19);
calendar.set(Calendar.MINUTE, 40);
calendar.set(Calendar.SECOND, 0);
PendingIntent slPendingIntent = PendingIntent.getService(this, 1, slIntent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager=(AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, slPendingIntent);
I tried a lot To Start Service on Time So I Have one solution like
Calculate the difference between current time and selected time
from date picker "Return Long timeMileSec = Milliseconds" Difference
after this create a handler inside it and Sleep if "Milliseconds" seconds
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
CreateService();
getActivity().startService(intentServiceObj);
}
}, timeMileSec);
// Below is the service Methods.
private void CreateService() {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.add(Calendar.DAY_OF_YEAR, year);
cal.set(Calendar.HOUR_OF_DAY, hourScreen);
cal.set(Calendar.MINUTE, minuteScreen);
// cal.setTimeInMillis(timeselectedmillisecond);
Intent intent = new Intent(getActivity(),
ServiceDailyLocationUpdate.class);
pintent = PendingIntent.getService(getActivity(), 0, intent, 0);
alarm = (AlarmManager) getActivity().getSystemService(
Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.HOUR, 86000 * 1000,
pintent);
}
// Return Differnce between two date
private long calculateDateDiffSecond(String firstDate, String secondDate) {
long numberOfDays = 0;
String dateStart = firstDate;
String dateStop = secondDate;
Date d1 = null;
Date d2 = null;
try {
d1 = sdfTime.parse(dateStart);
d2 = sdfTime.parse(dateStop);
// in milliseconds
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.print(diffDays + " days, ");
System.out.print("Hours::" + diffHours + " hours, ");
System.out.print("HoursMinute::" + diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");
numberOfDays = diffDays;
numberOfDays = diff;
} catch (Exception e) {
e.printStackTrace();
}
return numberOfDays;
}
codes above didn't work and below code worked for me.
month decreases 1.
and hours 0-11.
int day = ff.getGregorianDay() ;
int month = ff.getGregorianMonth() ;
int year = ff.getGregorianYear();
int hour = TimePicker1.getCurrentHour();
int minute = TimePicker1.getCurrentMinute();
Calendar cal_alarm = Calendar.getInstance();
cal_alarm.setTimeInMillis(System.currentTimeMillis() );
cal_alarm.set(Calendar.YEAR, year);
cal_alarm.set(Calendar.MONTH, month-1);
cal_alarm.set(Calendar.DAY_OF_MONTH, day);
cal_alarm.set(Calendar.AM_PM, Calendar.AM );
cal_alarm.set(Calendar.HOUR, hour);
if( hour >= 12){
cal_alarm.set(Calendar.AM_PM, Calendar.PM );
cal_alarm.set(Calendar.HOUR, hour-12);
}
cal_alarm.set(Calendar.MINUTE, minute );
cal_alarm.set(Calendar.SECOND, 0 );
Intent myIntent = new Intent(YadavariNewActivity.this, Alarm_Sag.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(YadavariNewActivity.this, 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set( AlarmManager.RTC_WAKEUP, cal_alarm.getTimeInMillis(), pendingIntent);

How do I set notification in android application at specific time?

I have used following code in android application to set up Notification(Alarm) using AlarmManager.
public void setAlarm() {
Intent intent = new Intent(MainActivity.this, TimeAlarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
(40000), pendingIntent);
}
Or should I use following code
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, 3);
calendar.set(Calendar.YEAR, 2015);
calendar.set(Calendar.DAY_OF_MONTH, 21);
calendar.set(Calendar.HOUR_OF_DAY,11);
calendar.set(Calendar.MINUTE, 15);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM,Calendar.AM);
Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
I want to set (notification)alarm at this specific time : 11:15AM on 21-March-2015
Can any one help me to set this?
First you need to use Calendar to set your date something like:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, 3);
cal.set(Calendar.YEAR, 2015);
cal.set(Calendar.DAY_OF_MONTH, 15);
cal.set(Calendar.HOUR_OF_DAY, 11);
cal.set(Calendar.MINUTE, 15);
And then in your setAlarm() method you need to set the alarm only once. You don't need to repeat it so:
public void setAlarm() {
Intent intent = new Intent(MainActivity.this, TimeAlarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
am.set(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(),pendingIntent);
}
Use alarm manager with service.
Service will introduce in manifest file.
Please follow below tutorial care fully.
A. http://nnish.com/2014/12/16/scheduled-notifications-in-android-using-alarm-manager/
B. http://androidideasblog.blogspot.co.uk/2011/07/alarmmanager-and-notificationmanager.html
C. https://github.com/benbahrenburg/benCoding.AlarmManager
D. http://www.banane.com/2014/05/07/simple-example-of-scheduled-self-clearing-android-notifications/
I hope it will help for you.
Run one thread every second and compare your specified time with current time, and if matches set notification.
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm aa");
String dateTimeinSrting = "21-Mar-2015 11:15 am";
try {
Date dateTime = formatter.parse(dateTimeInString);
} catch (ParseException e) {
e.printStackTrace();
}
float dateTimeInMillis = dateTime.getTime();
handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
Calendar calendar;
if(Float.compare(dateTimeInMillis, calendar.getTimeInMillis())){
//Set the notification here
}
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 1000);

Alarm Manager is triggered immediately in Android

Strangely, my Alarm Manger is calling the pending intent immediately, even though I have put a condition if the current time is greater than alarm time run one day later.
I have alarm Manger to trigger everyday at 10PM.
Intent startServiceIntent = new Intent(this, numbers.class);
this.startService(startServiceIntent);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(res.getString(R.string.hoursvalue))); //10
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.AM_PM, Calendar.PM);
cal.set(Calendar.MILLISECOND, 0);
long alarmtime = cal.getTimeInMillis();
Log.e("ALarm","Time"+alarmtime);
if (currenttime > alarmtime)
{
alarmtime = alarmtime + AlarmManager.INTERVAL_DAY;
Log.e("Current Time","Greater"+alarmtime);
}
if (currentapiVersion >= 19)
{
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent2 = new Intent(this, ServiceForLoadingOnlineNumbers.class);
PendingIntent pi = PendingIntent.getService(this, 741258963, intent2, 0);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, alarmtime, AlarmManager.INTERVAL_DAY, pi);
}
else if (currentapiVersion >= 16 && currentapiVersion < 19)
{
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent3 = new Intent(this, ServiceForLoadingOnlineNumbers.class);
PendingIntent pi = PendingIntent.getService(this, 741258963, intent3, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, alarmtime, AlarmManager.INTERVAL_DAY, pi);
}
The Log shows the next day in milliseconds correctly but triggers immediately. What could be the issue here?
Try to use this way and let me know if you face any issues
Date dat = new Date();// initializes to now
Calendar cal_alarm = Calendar.getInstance();
Calendar cal_now = Calendar.getInstance();
cal_now.setTime(dat);
Toast.makeText(mContext, "" + cal_now.getTime(), Toast.LENGTH_LONG)
.show();
;
cal_alarm.setTime(dat);
cal_alarm.set(Calendar.HOUR_OF_DAY, 13);// set the alarm time
cal_alarm.set(Calendar.MINUTE, 10);
cal_alarm.set(Calendar.SECOND, 10);
if (cal_alarm.before(cal_now)) {// if its in the past increment
cal_alarm.add(Calendar.DATE, 1);
}
I suggest checking if the alarm manager is null then canceling the alarm before setting the alarm this took me some time example
if(alarmManger != null){
alarmManger.cancel(operation);
alarmManger.setRepeating(alarmType,alarmtime,‌​AlarmManager.INTERVAL_DAY, operation);
}

Using Alarmmanager to start a service at specific time

I have searched a lot of places but couldnt find a clean sequential explanation of how to start a service (or if thats not possible then an activity) at a specific time daily using the AlarmManager??
I want to register several such alarms and triggering them should result in a service to be started. I'll be having a small piece of code in the service which can then execute and i can finish the service for good....
Calendar cal = Calendar.getInstance();
Calendar cur_cal = Calendar.getInstance();
cur_cal.setTimeInMillis(System.currentTimeMillis());
Date date = new Date(cur_cal.get(Calendar.YEAR), cur_cal.get(Calendar.MONTH), cur_cal.get(Calendar.DATE), 16, 45);
cal.setTime(date);
Intent intent = new Intent(ProfileList.this, ActivateOnTime.class);
intent.putExtra("profile_id", 2);
PendingIntent pintent = PendingIntent.getService(ProfileList.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pintent);
System.out.println("The alarm set!!");
i tried this code to activate the alarm at 4.45... but its not firing the service... do i have to keep the process running??
M i doing anything wrong???
One more thing, my service gets perfectly executed in case i use the following code:
long firstTime = SystemClock.elapsedRealtime();
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 30*1000,pintent);
HI friends,
After a lot of researching and with reference from "Pentium10"'s question on the same topic i managed to get it working. Though i still cant understand why the "date" concept and the Calendar(non GregorianCalendar) object which i have mentioned in the question are not working correctly.
Calendar cur_cal = new GregorianCalendar();
cur_cal.setTimeInMillis(System.currentTimeMillis());//set the current time and date for this calendar
Calendar cal = new GregorianCalendar();
cal.add(Calendar.DAY_OF_YEAR, cur_cal.get(Calendar.DAY_OF_YEAR));
cal.set(Calendar.HOUR_OF_DAY, 18);
cal.set(Calendar.MINUTE, 32);
cal.set(Calendar.SECOND, cur_cal.get(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cur_cal.get(Calendar.MILLISECOND));
cal.set(Calendar.DATE, cur_cal.get(Calendar.DATE));
cal.set(Calendar.MONTH, cur_cal.get(Calendar.MONTH));
Intent intent = new Intent(ProfileList.this, IntentBroadcastedReceiver.class);
PendingIntent pintent = PendingIntent.getService(ProfileList.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);
//Create alarm manager
AlarmManager alarmMgr0 = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
//Create pending intent & register it to your alarm notifier class
Intent intent0 = new Intent(this, AlarmReciever.class);
PendingIntent pendingIntent0 = PendingIntent.getBroadcast(this, 0, intent0, 0);
//set timer you want alarm to work (here I have set it to 7.20pm)
Intent intent0 = new Intent(this, OldEntryRemover.class);
Calendar timeOff9 = Calendar.getInstance();
timeOff9.set(Calendar.HOUR_OF_DAY, 19);
timeOff9.set(Calendar.MINUTE, 20);
timeOff9.set(Calendar.SECOND, 0);
//set that timer as a RTC Wakeup to alarm manager object
alarmMgr0.set(AlarmManager.RTC_WAKEUP, timeOff0.getTimeInMillis(), pendingIntent0);
Then in your AlarmReciever class which is a broadcastReciever, under onRecieve method put your logic. This will take care of what ever the logic you want to handle when the time comes to 7.20 pm.
If you need to set multiple alarms, create another Calendar instance & set time values appropriately. You also need to create another instance for pendingIntent otherwise timers will overlap. Then set it to same alarmManager with new timer & pendingIntent.
You can read document from https://developer.android.com/training/scheduling/alarms.html
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
// Set the alarm to start at 8:30 a.m.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 30);
// setRepeating() lets you specify a precise custom interval--in this case,
// 20 minutes.
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
1000 * 60 * 20, alarmIntent);
The following code should work fine and it starts the service # 7:40 PM every day. Also, if device shuts down then all your alarms get cancelled.
Make sure to set up all the alarms after BOOT is completed.
Intent slIntent = new Intent(this, x.class);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 19);
calendar.set(Calendar.MINUTE, 40);
calendar.set(Calendar.SECOND, 0);
PendingIntent slPendingIntent = PendingIntent.getService(this, 1, slIntent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager=(AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, slPendingIntent);
I tried a lot To Start Service on Time So I Have one solution like
Calculate the difference between current time and selected time
from date picker "Return Long timeMileSec = Milliseconds" Difference
after this create a handler inside it and Sleep if "Milliseconds" seconds
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
CreateService();
getActivity().startService(intentServiceObj);
}
}, timeMileSec);
// Below is the service Methods.
private void CreateService() {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.add(Calendar.DAY_OF_YEAR, year);
cal.set(Calendar.HOUR_OF_DAY, hourScreen);
cal.set(Calendar.MINUTE, minuteScreen);
// cal.setTimeInMillis(timeselectedmillisecond);
Intent intent = new Intent(getActivity(),
ServiceDailyLocationUpdate.class);
pintent = PendingIntent.getService(getActivity(), 0, intent, 0);
alarm = (AlarmManager) getActivity().getSystemService(
Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.HOUR, 86000 * 1000,
pintent);
}
// Return Differnce between two date
private long calculateDateDiffSecond(String firstDate, String secondDate) {
long numberOfDays = 0;
String dateStart = firstDate;
String dateStop = secondDate;
Date d1 = null;
Date d2 = null;
try {
d1 = sdfTime.parse(dateStart);
d2 = sdfTime.parse(dateStop);
// in milliseconds
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.print(diffDays + " days, ");
System.out.print("Hours::" + diffHours + " hours, ");
System.out.print("HoursMinute::" + diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");
numberOfDays = diffDays;
numberOfDays = diff;
} catch (Exception e) {
e.printStackTrace();
}
return numberOfDays;
}
codes above didn't work and below code worked for me.
month decreases 1.
and hours 0-11.
int day = ff.getGregorianDay() ;
int month = ff.getGregorianMonth() ;
int year = ff.getGregorianYear();
int hour = TimePicker1.getCurrentHour();
int minute = TimePicker1.getCurrentMinute();
Calendar cal_alarm = Calendar.getInstance();
cal_alarm.setTimeInMillis(System.currentTimeMillis() );
cal_alarm.set(Calendar.YEAR, year);
cal_alarm.set(Calendar.MONTH, month-1);
cal_alarm.set(Calendar.DAY_OF_MONTH, day);
cal_alarm.set(Calendar.AM_PM, Calendar.AM );
cal_alarm.set(Calendar.HOUR, hour);
if( hour >= 12){
cal_alarm.set(Calendar.AM_PM, Calendar.PM );
cal_alarm.set(Calendar.HOUR, hour-12);
}
cal_alarm.set(Calendar.MINUTE, minute );
cal_alarm.set(Calendar.SECOND, 0 );
Intent myIntent = new Intent(YadavariNewActivity.this, Alarm_Sag.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(YadavariNewActivity.this, 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set( AlarmManager.RTC_WAKEUP, cal_alarm.getTimeInMillis(), pendingIntent);

Categories

Resources