This Method is in MyClass.java that extends Service
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
settPeriodicService = this;
HOUR = 0;
MINUTE = 0;
message="Happy birthday!";
if(running) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,HOUR);
calendar.set(Calendar.MINUTE,MINUTE);
calendar.set(Calendar.SECOND,0);
calendar.set(Calendar.DAY_OF_YEAR,1);
Intent i = new Intent(this, MyService.class);
PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);
running = true;
}
return super.onStartCommand(intent, flags, startId);
}
Why does MyService start immediately?
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,HOUR);
calendar.set(Calendar.MINUTE,MINUTE);
calendar.set(Calendar.SECOND,0);
calendar.set(Calendar.DAY_OF_YEAR,1);
Above calendar represents a time in the past because you set the day to january 1st with calendar.set(Calendar.DAY_OF_YEAR,1);. Setting a time in the past will trigger the alarm immediately.
You probably want to do this:
calendar.add(Calendar.DAY_OF_YEAR,1);
to set the calendar to tomorrow.
Related
I'm trying to make alarms using the times provided in the sqlite database for the reminders. however I can't seem to be getting it right. the code I have so far is: (in my mainactivity oncreate)
for (int i = 0; i < allRems.size(); i++) {
int mHour = 0, mMin = 0;
String mAlarmTime = allRems.get(i).getRemTime();
int mID = allRems.get(i).getRemId();
if (!(mAlarmTime == null)) {
String[] time = mAlarmTime.split(":");
mHour = Integer.parseInt(time[0].trim());
mMin = Integer.parseInt(time[1].trim());
}
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, mHour);
calendar.set(Calendar.MINUTE, mMin);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent alarmIntent = new Intent(getApplicationContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, mID, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
}
and my alarm receiver class is
#Override
public void onReceive(Context context, Intent intent) {
Log.e("onReceive", "--------------------------------------------------------");
Toast.makeText(context, "OnReceive alarm test", Toast.LENGTH_LONG).show();
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
Log.e("DEVICE: ", "Device Rebooted");
}
}
i want to be able to set reminders for the specific time for the reminders in the database
I'm trying to create 3 notifications after the desired date and time is selected from a datepicker and a timepicker. I want to send notifications for the last 3 days for the selected value. But after the 3 notifications I want to cancel the notification process. I set up my pending notification and an alarm manager from my activity like
TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
//last 3 days add notification
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day, hourOfDay, minute, 0);
long when = calendar.getTimeInMillis();
when = when -3*(24*60*60*1000)+3000; //set startup time 3 days before
GetTime(when);
long diff = when - Calendar.getInstance().getTimeInMillis();
while (diff < 0){
when+= (24*60*60*1000); //increment 24h if selected time is closer then 3 days
diff = when - Calendar.getInstance().getTimeInMillis();
GetTime(when);
}
if (diff >0) {
Intent notifyIntent = new Intent(getApplicationContext() ,NotificationReceiver.class);
notifyIntent.putExtra("ctg", categorySelected);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), new Utils().getIdForCategory(categorySelected), notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when, 60*1000, pendingIntent); //setting for testing purposes for 60 seconds
}
}
};
My receiver class is :
protected void onHandleIntent(Intent intent) {
String categorySelected = intent.getStringExtra("ctg");
SharedPreference pref = new SharedPreference(getApplicationContext());
int alarmCount = pref.getAlarmCount(categorySelected);
if (alarmCount<=3){
Log.d("alarmCount", String.valueOf(alarmCount));
pref.saveAlarmCount(categorySelected,alarmCount+1);
showNotification(intent);
}
else //we reached the 3 times
{
new Utils().clearAllPendingIntent(getApplicationContext(),categorySelected);
}
}
and my clear method
public void clearAllPendingIntent(Context context, String categorySelected){
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent notifyIntent = new Intent(context ,NotificationReceiver.class);
notifyIntent.putExtra("ctg",categorySelected);
PendingIntent pendingUpdateIntent = PendingIntent.getBroadcast(context, new Utils().getIdForCategory(categorySelected), notifyIntent, PendingIntent.FLAG_CANCEL_CURRENT);
SharedPreference pref = new SharedPreference(context);
pref.saveAlarmCount(categorySelected,1);
// Cancel alarms
try {
alarmManager.cancel(pendingUpdateIntent);
} catch (Exception e) {
}
}
My problem is that the pending intent is not canceled after 3 times, which means I get notification each minute. What am I doing wrong?
The actual problem was with my new Utils().getIdForCategory(categorySelected) function which should return a specific value based on the category.
public int getIdForCategory(String category){
if (category.equals("A")) return 1; //before it was category=="A"
if (category.equals("B")) return 2;
if (category.equals("C")) return 3;
if (category.equals("D")) return 4;
if (category.equals("E")) return 5;
return 0;
}
I am trying to create a Scheduler in AKKA.
Requirement is :-
It will start every day 5:00AM
It will stop at 10:00 PM every day
It will execute job in every 1 hr (Frequency).
I find the solution for 3rd point (Frequency) but not able to find the solution for 1st and 2nd point.
system.scheduler().schedule(Duration.create(10, TimeUnit.SECONDS), Duration.create(1, TimeUnit.HOURS), actorRef, "Hello", system.dispatcher(), null);
// For 5.00 am time period.
int InHrs = 17;
int InMinutes = 00;
scheduler = Akka.system().scheduler().schedule(Duration.create(nextExecutionInSeconds(InHrs, InMinutes), TimeUnit.SECONDS),
Duration.create(24, TimeUnit.HOURS),
new Runnable() {
#Override
public void run() {
// Call your method
System.out.println("EVERY 24:00 Later --- " + System.currentTimeMillis());
}
},
Akka.system().dispatcher());
public static int nextExecutionInSeconds(int hour, int minute){
return Seconds.secondsBetween(
new DateTime(),
nextExecution(hour, minute)
).getSeconds();
}
public static DateTime nextExecution(int hour, int minute){
DateTime next = new DateTime()
.withHourOfDay(hour)
.withMinuteOfHour(minute)
.withSecondOfMinute(0)
.withMillisOfSecond(0);
return (next.isBeforeNow())
? next.plusHours(24)
: next;
}
Repeat this for 10 AM time period which will be 22 inHrs. Hopefully it solves the problem.
// I am using this for scheduling and repeating, it is working fine
//**I am also searching for to Stop Scheduler after Specific Time**
public static void setReminder(Context context, Class<?> cls, int hour, int min, int uniqueAlertID)
{
Calendar calendar = Calendar.getInstance();
Calendar setcalendar = Calendar.getInstance();
setcalendar.set(Calendar.HOUR_OF_DAY, hour);
setcalendar.set(Calendar.MINUTE, min);
setcalendar.set(Calendar.SECOND, 0);
// cancel already scheduled reminders
cancelReminder(context,cls, uniqueAlertID);
if(setcalendar.before(calendar))
setcalendar.add(Calendar.DATE,1);
// Enable a receiver
ComponentName receiver = new ComponentName(context, cls);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
Intent intent1 = new Intent(context, cls);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, uniqueAlertID, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, setcalendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent);
}
public static void cancelReminder(Context context,Class<?> cls, int uniqueAlertID)
{
// Disable a receiver
ComponentName receiver = new ComponentName(context, cls);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
Intent intent1 = new Intent(context, cls);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
uniqueAlertID, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
am.cancel(pendingIntent);
pendingIntent.cancel();
}
I am new to android programming. I want to set different repeating alarms. I wrote a code, but it is not working. It is not generating any alarms. Please help me.
Here is my code
public void setAlarm(int hour, int min,String am_pm){
if(hour == 12 && am_pm.equals("am")){
hour=00;
}
if(hour != 12 && am_pm.equals("pm")){
hour=hour+12;
}
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, min);
Intent intent = new Intent(getBaseContext(), AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), (int) System.currentTimeMillis(), intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
For above I am passing setAlarm(8,30,"am")
My task is to run service even if app is closed.
My service class:
public class MyService extends Service {
public int onStartCommand(Intent intent, int flags, int startId) {
AudioManager am;
am= (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
if(am.getRingerMode() == AudioManager.RINGER_MODE_NORMAL)
am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
else
am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Minute minute = new Minute();
Calendar cal = Calendar.getInstance();
AlarmManager alarms ;
Intent activate = new Intent(this, MyService.class);
PendingIntent alarmIntent = PendingIntent.getService(this, 0, activate, 0);
alarms = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
cal.set(Calendar.HOUR_OF_DAY, 00);
cal.set(Calendar.MINUTE, minute.minute);
cal.set(Calendar.SECOND, 00);
alarms.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), alarmIntent);
Toast.makeText(this, "checkOnStart", Toast.LENGTH_LONG).show();
return Service.START_STICKY;
}
}
In my activity:
Intent activate = new Intent(this, MyService.class);
startService(activate);
i try to use foreground Service it's doesnt help me
But when I kill the app the service closed, what should I do to keep the service running after the app is killed?