Android set repeating alarm for certain time of day - android

I am trying to set a repeating alarm that will will download a file every minute but only between 8:00 and 22:00. I feel like I'm really close but I can't see the error I'm making. Currently the broadcast receiver is not activating. If set the repeating alarm manually to alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+10000, 60000,pendingIntent); it works fine. Any guidance would be much appreciated.
protected void scheduleNextUpdate()
{
Intent intent = new Intent("TEST");
PendingIntent pendingIntent =
PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
int updateInterval = 1;
long nextUpdate =(60000 * updateInterval);
long currentTimeMillis = System.currentTimeMillis();
long nextUpdateTimeMillis = currentTimeMillis + nextUpdate;
Time nextUpdateTime = new Time();
nextUpdateTime.set(nextUpdateTimeMillis);
if (nextUpdateTime.hour < 8 || nextUpdateTime.hour > 22)
{
nextUpdateTime.hour = 8;
nextUpdateTime.minute = 0;
nextUpdateTime.second = 0;
nextUpdateTimeMillis = nextUpdateTime.toMillis(false) + DateUtils.DAY_IN_MILLIS;
}
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+10000, nextUpdateTimeMillis,pendingIntent);
boolean alarmUp = (PendingIntent.getBroadcast(this, 0,
new Intent("TEST"),
PendingIntent.FLAG_NO_CREATE) != null);
if (alarmUp)
{
Log.d("myTag", "Alarm is already active");
}
}

You should set your alarm reapeating when it is between 8:00 and 22:00 like you mentioned:
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+10000, 60000,pendingIntent);
This will repeat every minute. But you must explicitly cancel the alarm. You can cancel it after download is completed, by checking if its already 22:00. Or by another alarm that will be triggered when it is 22:00. Otherwise it will not stop.
use alarmManager.cancel (pendingIntent)
described here: http://developer.android.com/reference/android/app/AlarmManager.html#cancel(android.app.PendingIntent
Hope this helps.

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

AlarmManager shifts time by 12 hours

I'm trying to create periodical notifications.
So, I created a function to reschedule new notification time:
private void rescheduleNotification(Context context) {
long nextNotifTime = System.currentTimeMillis();
// Schedule next notification in 15 minutes
nextNotifTime += 15 * 60 * 1000;
Calendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(nextNotifTime);
// It's an old version with the same result
//calendar.add(Calendar.MINUTE, 15);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy HH:mm:ss", Locale.ENGLISH);
this.logEvent(" Next notification time is: " + sdf.format(calendar.getTimeInMillis()));
Intent intent = new Intent(context, WordsBcReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager manager = (AlarmManager)context.getSystemService(ALARM_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= 23) {
manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, nextNotifTime, pendingIntent);
} else {
manager.set(AlarmManager.RTC_WAKEUP, nextNotifTime, pendingIntent);
}
this.logEvent(" Set next notification time: " + sdf.format(nextNotifTime));
}
Sometimes it runs correctly, but sometimes notification time shifts by exactly 12 hours.
I added special function to log all time manipulations, so the log contains:
29/12/17 11:30:36: Next notification time is: 29/12/17 12:00:36
29/12/17 11:30:36: Set next notification time: 29/12/17 12:00:36
seems OK, but adb shell dumpsys alarm says:
type=0 whenElapsed=+11h34m13s906ms when=2017-12-30 00:00:36
I tried to use Calendar (I to exclude some periods later), but result was the same.
Can't find the problem...

Starting alarm after specified days

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

Repeating alarm wont work in Android

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

Alarm does not make itself visible

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?

Categories

Resources