Starting alarm after specified days - android

Hello Below is my code to Start the alarm in my application.
public static void startReferAlarm(Context context,String[] message,String activityToOpen)
{
try {
Log.d("Refer friend Activity", "Alarm On");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
Intent myIntent = new Intent(context, AlarmReciever.class);
myIntent.putExtra("message",message);
myIntent.putExtra("äctivityName",activityToOpen);
final int _id = (int) System.currentTimeMillis();
PendingIntent appIntent = PendingIntent.getBroadcast(context, _id, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//48*60*60*1000
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
48*60*60*1000, appIntent);
}catch (Exception e) {
Log.d("MyActivity", "Alarm Off");
e.printStackTrace();
}
}
From my understating above code will start the alarm and will notify on 8 am. and then will repeat after 48 hours.
But I want to start the alarm after 48 hours or lets say after 7 hours and then it repeat after every 48 hours.
Please help me with the logic.Thanks in advance.

Do not use calender.set(Calendar.HOUR, 8) as it will set hours to 8'o clock
Try
//if you want to add 7 hours
calender.add(Calender.HOUR, 7); //this will add 7 hours to current time
//if you want to add 7 days
calender.add(Calender.DAY_OF_MONTH, 7); //this will add 7 days to current time
// interval to repeat alarm after 48hours
int interval = 48 * 60 * 60 * 1000;
Replace Calendar.HOUR with Calendar.HOUR_OF_THE_DAY if you want to use it in 24hours format.
See the answer for repeating alarm issue How to repeat alarm in android 6.0

For any one who is still confuse. Below method will initiate the alarm after 7 days of any particular action it will notify on 9 am and will repeat after 48 hours.
public static void startCreateProfileAlarm(Context context,AlarmManager alarmManager ,String[] message,String activityToOpen) {
try {
//working code
Calendar calendar = Calendar.getInstance();
calendar.add(DAY_OF_MONTH,7);
//calendar.add(Calendar.HOUR_OF_DAY,1);
calendar.set(Calendar.HOUR_OF_DAY, 9);
// we can set any time here
//calendar.set(Calendar.HOUR_OF_DAY, 10);
Intent myIntent = new Intent(context, AlarmReciever.class);
myIntent.putExtra("message",message);
myIntent.putExtra("äctivityName",activityToOpen);
final int _id = (int) System.currentTimeMillis();
createProfileAppIntent = PendingIntent.getBroadcast(context, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//48*60*60*1000
//2*60*1000
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
48*60*60*1000, createProfileAppIntent);
}catch (Exception e) {
Log.d("MyActivity", "Alarm Off");
e.printStackTrace();
}
}

Related

Change textview everyday automatically

First I want to change textview text everyday automatically. For example, first day the textview text is "First text", and second day text is "Second text" at 8 o'clock eveyday. And the text is permanent until next day 8 o'clock.
I try this code but my problem is that the code is not triggered if the user doesn't open this page at 8 o'clock. Texts are inside "mquote array"
SharedPreferences pref =getApplicationContext().getSharedPreferences("myPrefsKey",Context.MODE_PRIVATE) ;
dayCount = pref.getInt("dayCount", 0);
Calendar cal = Calendar.getInstance();
int hour=cal.get(Calendar.HOUR_OF_DAY);
int minute=cal.get(Calendar.MINUTE);
if ((hour==8 && minute==1 ))
updateQuote();
tvQuote.setText(mquote.getQuote(dayCount));
public void updateQuote()
{
if (dayCount==4)
dayCount=0;
dayCount++;
pref.edit().putInt("dayCount",dayCount).apply();
}
You need an AlarmManager implementation:
public class AlarmReceiver extends BroadcastReceiver {
// The app's AlarmManager, which provides access to the system alarm services.
private AlarmManager alarmMgr;
// The pending intent that is triggered when the alarm fires.
private PendingIntent alarmIntent;
public void setAlarm(Context context) {
alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
// set the Alarm's trigger time to 8:00 a.m.
calendar.set(Calendar.HOUR_OF_DAT, 9);
// Set the alarm to fire at approximately 8:30 a.m., according to the device's
// clock, and to repeat once a day.
alarmManager.setInexactRepeating(AlarmManager.RTC,
calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmIntent);
}
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED"))
{
alarm.setAlarm(context);
} else if(Objects.equals(intent, alarmIntent)) {
SharedPreferences pref = getApplicationContext().getSharedPreferences("key", Context.MODE_PRIVATE);
int dayCount = pref.getInt("dayCount", 0);
dayCount %= 4;
pref.edit().putInt("dayCount", ++daysCount).apply();
}
}
}
You should use timestamp to be able to compare two dates. try this code.
But the 1 day happens while user is using the app, it will not trigger. If you want to overcome this, then use AlarmManager to trigger an event every single day.
SharedPreferences pref = getApplicationContext().getSharedPreferences("myPrefsKey",Context.MODE_PRIVATE);
lastDay_ms= pref.getInt("time_ms", 0);
Calendar today = Calendar.getInstance();
long diff = today.getTimeInMillis() - lastDay_ms; //result in millis
final long ONE_DAY = 24*60*60*1000; //millis in a day
if (diff > ONE_DAY)
updateQuote();
Store milliseconds when you last updated preferences in your preferences:
SharedPreferences pref = getApplicationContext().getSharedPreferences("msKey", Context.MODE_PRIVATE);
msCount = pref.getInt("msCount", 0);
long milliseconds = System.currentTimeMillis();
long diff = milliseconds - msCount;
diff += (8 * 60 * 60 * 1000); // compensating difference for 8'O clock condition
int days = (int) Math.ceil(diff / 24 / 60 / 60 / 1000);
days %= 4; // Because you were resetting days count after 4 increments
updateQuote(days);
public void updateQuote(days) {
if(days == 0) {
pref.edit().putInt("msCount", milliseconds).apply();
}
}

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);

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