I have set notifications using alarm manager for events. If I set multiple notifications at different times then last all notifications also arise at last notification with the last one.
Also I want to cancel the particular notification if the switch is off. I have given the same intent to cancel the notification. But I think all the notifications got cancelled.
Also I have created time tables and events are created using the time table's id. Now if I delete one time table I want to delete all the notifications set to the events that belongs to the deleted time table.
setting alarm:
public void setNotificationTime(Calendar c)
{
Date dateFrom = new Date();
df = new SimpleDateFormat("E MMM dd HH:mm:ss zzzz yyyy");
try {
dateFrom = df.parse(startTime);
}
catch (ParseException ex) {
}
dateFrom.getTime();
c.setTime(dateFrom);
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
if(notificationTime !=null && !notificationTime.isEmpty()) {
if (notificationTime.equals("10 Minutes Before")) {
FLAG = 1;
c.set(Calendar.HOUR_OF_DAY, hour);
c.set(Calendar.MINUTE, minute - 10);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
c.set(Calendar.DATE, day);
// c.set(Calendar.DAY_OF_WEEK,);
SetDay(c);
notification = c.getTime();
notificationTime = df.format(notification);
// setAlarm(c, FLAG);
Intent intent = new Intent(getBaseContext(), NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 7, pendingIntent);
Toast.makeText(getApplicationContext(), notificationTime, Toast.LENGTH_SHORT).show();
} else if (notificationTime.equals("30 Minutes Before")) {
FLAG = 2;
c.set(Calendar.HOUR_OF_DAY, hour);
c.set(Calendar.MINUTE, minute - 30);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
c.set(Calendar.DATE, day);
// c.set(Calendar.DAY_OF_WEEK,);
SetDay(c);
notification = c.getTime();
notificationTime = df.format(notification);
Intent intent = new Intent(getBaseContext(), NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 7, pendingIntent);
Toast.makeText(getApplicationContext(), notificationTime, Toast.LENGTH_SHORT).show();
// setAlarm(c,FLAG);
}
Notification Receiver
public class NotificationReceiver extends BroadcastReceiver {
public static int MY_NOTIFICATION_ID = 0;
NotificationManager notificationManager;
Notification myNotification;
EventTableHelper db;
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Time is set", Toast.LENGTH_LONG).show();
db = new EventTableHelper(context);
List<EventData> testSavings = db.getAllEvents();
for (EventData ts : testSavings) {
String log = "from date:" + ts.getFromDate()
+ " ,to date: " + ts.getToDate()
+ " ,location: " + ts.getLocation()
+ " ,title " + ts.getTitle();
Calendar c = Calendar.getInstance();
Date date = new Date();
Date date1 = new Date();
Log.d("Result: ", log);
SimpleDateFormat df = new SimpleDateFormat("E MMM dd hh:mm:ss zzzz yyyy");
SimpleDateFormat df2 = new SimpleDateFormat("hh:mm a");
try {
date = df.parse(ts.getFromDate());
date1 = df.parse(ts.getToDate());
} catch (ParseException ex) {
}
String timeFrom = df2.format(date);
// String startTime = String.valueOf(timeFrom);
String timeTo = df2.format(date1);
// String endTime = String.valueOf(timeTo);
String location = ts.getLocation();
String title = ts.getTitle();
Intent myIntent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
context,
0,
myIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
if(location.equals(""))
{
String msg = "From : " + timeFrom + "\nTo : " + timeTo;
myNotification = new NotificationCompat.Builder(context)
.setContentTitle("Event : " + title)
.setContentText(msg)
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setSmallIcon(R.drawable.eventicon)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setDefaults(Notification.DEFAULT_SOUND)
.build();
}
else
{
String msg = "From : " + timeFrom + "\nTo : " + timeTo + "\nAt : " + location;
myNotification = new NotificationCompat.Builder(context)
.setContentTitle("Event : " + title)
.setContentText(msg)
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setSmallIcon(R.drawable.eventicon)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setDefaults(Notification.DEFAULT_SOUND)
.build();
}
Log.i("Notify", "Notification");
notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
myNotification.flags=Notification.FLAG_AUTO_CANCEL;
Intent i = new Intent();
i.putExtra("notificationId",MY_NOTIFICATION_ID);
MY_NOTIFICATION_ID ++;
}
}
}
You reset MY_NOTIFICATION_ID every time the broadcastReceiver is called so all the notifications have the same id, which is 0.
What I did to avoid it was to use:
Random rand = new Random();
int id = rand.nextInt(1000000) + 1;
so that every notification will definitely get a different id number (chance of 1 in a million it will repeat itself).
Related
I am creating a school application in which when i visit there for
marketing i have to submit a report every time. If visit is
Successful then there is no issue if visit is unsuccessful then i
have to reschedule my meeting for next visit. When i set date and
time for my next meeting it should remind me in early morning by
sending a notification and it should alarm at that time so i can get
reminder. here is my code for report Activity please help me
private void sendNotificationDetailsTwo() {
/* Calendar firingCal = Calendar.getInstance();
Calendar currentCal = Calendar.getInstance();
firingCal.set(Calendar.HOUR_OF_DAY, 8); // At the hour you wanna fire
firingCal.set(Calendar.MINUTE, 30); // Particular minute
firingCal.set(Calendar.SECOND, 0); // particular second
Long intendedTime = firingCal.getTimeInMillis();
if (firingCal.compareTo(currentCal) < 0) {
firingCal.add(Calendar.DAY_OF_MONTH, 1);
} else {
for (int i = 0; i < 10; ++i) {
Intent newIntentTwo = new Intent(Report_Activity.this, MyReceiver.class);
final int intent_id_two = (int) System.currentTimeMillis();
newIntentTwo.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
Bundle bundle = new Bundle();
bundle.putString("date", str_view_date);
bundle.putString("time", str_view_time);
bundle.putString("school_name", str_show_school_name);
bundle.putInt("intent_id", intent_id_two);
newIntentTwo.putExtras(bundle);
AlarmManager alarmManager = (AlarmManager) Report_Activity.this.getSystemService(Report_Activity.this.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(Report_Activity.this, intent_id_two, newIntentTwo, PendingIntent.FLAG_ONE_SHOT);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent);
}
}*/
/*alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); alarmIntent = new Intent(context of current file, AlarmReceiver1.class); // AlarmReceiver1 = broadcast receiver
pendingIntent = PendingIntent.getBroadcast( Menu.this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmIntent.setData((Uri.parse("custom://"+System.currentTimeMillis())));
alarmManager.cancel(pendingIntent);
Calendar alarmStartTime = Calendar.getInstance();
Calendar now = Calendar.getInstance();
alarmStartTime.set(Calendar.HOUR_OF_DAY, 8);
alarmStartTime.set(Calendar.MINUTE, 00);
alarmStartTime.set(Calendar.SECOND, 0);
if (now.after(alarmStartTime)) {
Log.d("Hey","Added a day");
alarmStartTime.add(Calendar.DATE, 1);
}
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarmStartTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
Log.d("Alarm","Alarms set for everyday 8 am.");*/
Calendar firingCal = Calendar.getInstance();
Calendar now = Calendar.getInstance();
firingCal.set(Calendar.HOUR_OF_DAY,15);
firingCal.set(Calendar.MINUTE,25);
firingCal.set(Calendar.SECOND,0);
while(now.getTimeInMillis()>firingCal.getTimeInMillis()){
firingCal.add(Calendar.DATE,1);
}
Intent myInten = new Intent(Report_Activity.this,MyReceiver.class);
final int intent_id_two = (int) System.currentTimeMillis();
myInten.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
Bundle bundle = new Bundle();
bundle.putString("date", str_view_date);
bundle.putString("time", str_view_time);
bundle.putString("school_name", str_show_school_name);
bundle.putInt("intent_id", intent_id_two);
myInten.putExtras(bundle);
//final int intent_id_two = (int) System.currentTimeMillis();
PendingIntent myPendingIntent = PendingIntent.getBroadcast(Report_Activity.this,intent_id_two,myInten,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)Report_Activity.this.getSystemService(Report_Activity.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,firingCal.getTimeInMillis(),2000,myPendingIntent);
}
MyAlarmService.java
public class MyAlarmService extends Service {
private NotificationManager notificationManager;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
boolean alarm =(PendingIntent.getBroadcast(this,0,new Intent("Alarm"),PendingIntent.FLAG_NO_CREATE)==null);
if(alarm){
Intent mintent =new Intent("Alarm");
PendingIntent mpendingIntent = PendingIntent.getBroadcast(this,0,mintent,0);
Calendar mcalender = Calendar.getInstance();
mcalender.setTimeInMillis(System.currentTimeMillis());
mcalender.add(Calendar.SECOND,3);
AlarmManager malarmmanager = (AlarmManager)getSystemService(ALARM_SERVICE);
malarmmanager.setRepeating(AlarmManager.RTC_WAKEUP,mcalender.getTimeInMillis(),6000,mpendingIntent);
}
}
}
MyReceiver.java
public class MyReceiver extends BroadcastReceiver {
int MID = 0;
int m = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
String date, time, school_name;
PendingIntent pendingIntent;
int intent_id;
#Override
public void onReceive(Context context, Intent intent) {
// long when = System.currentTimeMillis();
Bundle bundle = intent.getExtras();
date = bundle.getString("date");
time = bundle.getString("time");
school_name = bundle.getString("school_name");
intent_id = bundle.getInt("intent_id");
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
//final int intent_id = (int) System.currentTimeMillis();
pendingIntent = PendingIntent.getActivity(context, intent_id, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(context)
.setContentTitle("Notification From Dextro")
.setContentText("Meeting Schedule at " + school_name + " on " + date + " and time is " + time)
.setSmallIcon(R.mipmap.dextro_customerlogo)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setSound(alarmSound)
.setTicker("Notification From Dextro")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText("Meeting Schedule at " + school_name + " on " + date + " and time is " + time))
.setVibrate(new long[]{100, 100, 100, 100});
notificationManager.notify(m, builder.build());
MID++;
}
}
1. In Simple way When i Reschedule my Work it should get notify me on
next morning with alarm
try this
.setVibrate(new long[]{0, 2000, 500, 2000, 500, 2000, 500});
try {
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.bells_bells_bells); //your sound file name from Raw folder
.setSound(uri);
} catch (Exception e) {
e.printStackTrace();
}
Working with Reminders taking two dates from user, first Start Reminder Date and second End Reminder Date
I have successfully written a code to start a reminder, repeat the reminder and now I would like to know How can I remove the reminder when comes to End date from database ?
I know, I have to use something like below to cancel an alarm (to delete reminder from database) but don't know where to use same code to delete reminder based on End date provided with reminder, click on link to see Activity code
for (int i = IDmap.size(); i >= 0; i--) {
int id = IDmap.get(i);
// Get reminder from reminder database using id
Reminder temp = rb.getReminder(id);
// Delete reminder
rb.deleteReminder(temp);
// Delete reminder alarm
mAlarmReceiver.cancelAlarm(getApplicationContext(), id);
}
AlarmReceiver.java:
public class AlarmReceiver extends WakefulBroadcastReceiver {
AlarmManager mAlarmManager;
PendingIntent mPendingIntent;
#Override
public void onReceive(Context context, Intent intent) {
int mReceivedID = Integer.parseInt(intent.getStringExtra(ReminderEditActivity.EXTRA_REMINDER_ID));
// Get notification title from Reminder Database
ReminderDatabase rb = new ReminderDatabase(context);
Reminder reminder = rb.getReminder(mReceivedID);
String mTitle = reminder.getTitle();
// Create intent to open ReminderEditOldActivity on notification click
Intent editIntent = new Intent(context, ReminderEditActivity.class);
editIntent.putExtra(ReminderEditActivity.EXTRA_REMINDER_ID, Integer.toString(mReceivedID));
PendingIntent mClick = PendingIntent.getActivity(context, mReceivedID, editIntent, PendingIntent.FLAG_UPDATE_CURRENT);
// Create Notification
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.setSmallIcon(R.drawable.ic_alarm_on_white_24dp)
.setContentTitle(context.getResources().getString(R.string.app_name))
.setTicker(mTitle)
.setContentText(mTitle)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(mClick)
.setAutoCancel(true)
.setOnlyAlertOnce(true);
NotificationManager nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nManager.notify(mReceivedID, mBuilder.build());
}
public void setAlarm(Context context, Calendar calendar, int ID) {
mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// Put Reminder ID in Intent Extra
Intent intent = new Intent(context, AlarmReceiver.class);
intent.putExtra(ReminderEditActivity.EXTRA_REMINDER_ID, Integer.toString(ID));
mPendingIntent = PendingIntent.getBroadcast(context, ID, intent, PendingIntent.FLAG_CANCEL_CURRENT);
// Calculate notification time
Calendar c = Calendar.getInstance();
long currentTime = c.getTimeInMillis();
long diffTime = calendar.getTimeInMillis() - currentTime;
// Start alarm using notification time
mAlarmManager.set(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + diffTime,
mPendingIntent);
// Restart alarm if device is rebooted
ComponentName receiver = new ComponentName(context, BootReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
}
public void setRepeatAlarm(Context context, Calendar calendar, int ID, long RepeatTime) {
mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// Put Reminder ID in Intent Extra
Intent intent = new Intent(context, AlarmReceiver.class);
intent.putExtra(ReminderEditActivity.EXTRA_REMINDER_ID, Integer.toString(ID));
mPendingIntent = PendingIntent.getBroadcast(context, ID, intent, PendingIntent.FLAG_CANCEL_CURRENT);
// Calculate notification timein
Calendar c = Calendar.getInstance();
long currentTime = c.getTimeInMillis();
long diffTime = calendar.getTimeInMillis() - currentTime;
// ensure the next alarm is in the future
while(diffTime < 0) {
diffTime += RepeatTime;
}
// Start alarm using initial notification time and repeat interval time
mAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + diffTime,
RepeatTime , mPendingIntent);
// Restart alarm if device is rebooted
ComponentName receiver = new ComponentName(context, BootReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
}
public void cancelAlarm(Context context, int ID) {
mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// Cancel Alarm using Reminder ID
mPendingIntent = PendingIntent.getBroadcast(context, ID, new Intent(context, AlarmReceiver.class), 0);
mAlarmManager.cancel(mPendingIntent);
// Disable alarm
ComponentName receiver = new ComponentName(context, BootReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
}
BootReceiver.java:
public class BootReceiver extends BroadcastReceiver {
private String mTitle;
private String mTime;
private String mDate;
private String mRepeatNo;
private String mRepeatType;
private String mActive;
private String mRepeat;
private String[] mDateSplit;
private String[] mTimeSplit;
private int mYear, mMonth, mHour, mMinute, mDay, mReceivedID, mEndDay, mEndMonth, mEndYear;
private long mRepeatTime;
private String mEndDate;
private String[] mEndDateSplit;
private Calendar mCalendar, mEndCalendar;
private AlarmReceiver mAlarmReceiver;
// Constant values in milliseconds
private static final long milMinute = 60000L;
private static final long milHour = 3600000L;
private static final long milDay = 86400000L;
private static final long milWeek = 604800000L;
private static final long milMonth = 2592000000L;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
ReminderDatabase rb = new ReminderDatabase(context);
mCalendar = Calendar.getInstance();
mEndCalendar = Calendar.getInstance();
mAlarmReceiver = new AlarmReceiver();
List<Reminder> reminders = rb.getAllReminders();
for (Reminder rm : reminders) {
mReceivedID = rm.getID();
mRepeat = rm.getRepeat();
mRepeatNo = rm.getRepeatNo();
mRepeatType = rm.getRepeatType();
mActive = rm.getActive();
mDate = rm.getDate();
mTime = rm.getTime();
mEndDate = rm.getmEndDate();
mDateSplit = mDate.split("/");
mTimeSplit = mTime.split(":");
mEndDateSplit = mEndDate.split("/");
mDay = Integer.parseInt(mDateSplit[0]);
mMonth = Integer.parseInt(mDateSplit[1]);
mYear = Integer.parseInt(mDateSplit[2]);
mEndDay = Integer.parseInt(mEndDateSplit[0]);
mEndMonth = Integer.parseInt(mEndDateSplit[1]);
mEndYear = Integer.parseInt(mEndDateSplit[2]);
mHour = Integer.parseInt(mTimeSplit[0]);
mMinute = Integer.parseInt(mTimeSplit[1]);
mCalendar.set(Calendar.MONTH, --mMonth);
mCalendar.set(Calendar.YEAR, mYear);
mCalendar.set(Calendar.DAY_OF_MONTH, mDay);
mCalendar.set(Calendar.HOUR_OF_DAY, mHour);
mCalendar.set(Calendar.MINUTE, mMinute);
mCalendar.set(Calendar.SECOND, 0);
mEndCalendar.set(Calendar.MONTH, --mEndMonth);
mEndCalendar.set(Calendar.YEAR, mEndYear);
mEndCalendar.set(Calendar.DAY_OF_MONTH, mEndDay);
mEndCalendar.set(Calendar.HOUR_OF_DAY, mHour);
mEndCalendar.set(Calendar.MINUTE, mMinute);
mEndCalendar.set(Calendar.SECOND, 0);
// Cancel existing notification of the reminder by using its ID
// mAlarmReceiver.cancelAlarm(context, mReceivedID);
// Check repeat type
if (mRepeatType.equals("Daily")) {
mRepeatTime = Integer.parseInt(mRepeatNo) * milDay;
} else if (mRepeatType.equals("Every 2 Days")) {
mRepeatTime = Integer.parseInt(mRepeatNo) * milDay;
} else if (mRepeatType.equals("Every 3 Days")) {
mRepeatTime = Integer.parseInt(mRepeatNo) * milDay;
} else if (mRepeatType.equals("Weekly")) {
mRepeatTime = Integer.parseInt(mRepeatNo) * milWeek;
} else if (mRepeatType.equals("Monthly")) {
mRepeatTime = Integer.parseInt(mRepeatNo) * milMonth;
}
// Create a new notification
if (mActive.equals("true")) {
if (mRepeat.equals("true")) {
mAlarmReceiver.setRepeatAlarm(context, mCalendar, mReceivedID, mRepeatTime);
} else if (mRepeat.equals("false")) {
mAlarmReceiver.setAlarm(context, mCalendar, mReceivedID);
}
}
}
}
}
}
UPDATED
#Override
public void onReceive(Context context, Intent intent) {
int mReceivedID = Integer.parseInt(intent.getStringExtra(ReminderEditActivity.EXTRA_REMINDER_ID));
// Get notification title from Reminder Database
ReminderDatabase rb = new ReminderDatabase(context);
Reminder reminder = rb.getReminder(mReceivedID);
String[] s = mEndDateSplit = mEndDate.split("/");
int mEndDay = Integer.parseInt(mEndDateSplit[0]);
int mEndMonth = Integer.parseInt(mEndDateSplit[1]);
int mEndYear = Integer.parseInt(mEndDateSplit[2]);
int mHour = Integer.parseInt(mTimeSplit[0]);
int mMinute = Integer.parseInt(mTimeSplit[1]);
Calendar mEndCalendar = Calendar.getInstance();
mEndCalendar.set(Calendar.MONTH, --mEndMonth);
mEndCalendar.set(Calendar.YEAR, mEndYear);
mEndCalendar.set(Calendar.DAY_OF_MONTH, mEndDay);
mEndCalendar.set(Calendar.HOUR_OF_DAY, mHour);
mEndCalendar.set(Calendar.MINUTE, mMinute);
mEndCalendar.set(Calendar.SECOND, 0);
String mRepeatNo = reminder.getRepeatNo();
if (mRepeatType.equals("Daily")) {
mRepeatTime = Integer.parseInt(mRepeatNo) * milDay;
} else if (mRepeatType.equals("Every 2 Days")) {
mRepeatTime = Integer.parseInt(mRepeatNo) * milDay;
} else if (mRepeatType.equals("Every 3 Days")) {
mRepeatTime = Integer.parseInt(mRepeatNo) * milDay;
} else if (mRepeatType.equals("Weekly")) {
mRepeatTime = Integer.parseInt(mRepeatNo) * milWeek;
} else if (mRepeatType.equals("Monthly")) {
mRepeatTime = Integer.parseInt(mRepeatNo) * milMonth;
}
if(SystemClock.elapsedRealtime() < mEndCalendar.getTimeInMillis()) {
String mTitle = reminder.getTitle();
// Create intent to open ReminderEditOldActivity on notification click
Intent editIntent = new Intent(context, ReminderEditActivity.class);
editIntent.putExtra(ReminderEditActivity.EXTRA_REMINDER_ID, Integer.toString(mReceivedID));
PendingIntent mClick = PendingIntent.getActivity(context, mReceivedID, editIntent, PendingIntent.FLAG_UPDATE_CURRENT);
// Create Notification
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.setSmallIcon(R.drawable.ic_alarm_on_white_24dp)
.setContentTitle(context.getResources().getString(R.string.app_name))
.setTicker(mTitle)
.setContentText(mTitle)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(mClick)
.setAutoCancel(true)
.setOnlyAlertOnce(true);
NotificationManager nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nManager.notify(mReceivedID, mBuilder.build());
}
if (reminder.getRepeat().equals("true")) {
if( SystemClock.elapsedRealtime() + mRepeatTime > mEndCalendar.getTimeInMillis()){
// The next alert will happen after the end time, cancel it and delete it from the database.
cancelAlarm(context, mReceivedID);
rb.deleteReminder(reminder);
}
} else {
// The alert isn't set to be repeated, cancel and delete it from the database.
cancelAlarm(context, mReceivedID);
rb.deleteReminder(reminder);
}
}
Here is what I've meant in the comment I've posted.
public class AlarmReceiver extends WakefulBroadcastReceiver {
...
#Override
public void onReceive(Context context, Intent intent) {
ReminderDatabase rb = new ReminderDatabase(context);
Reminder reminder = rb.getReminder(mReceivedID);
.......
if(rm.getRepeat().equals("true")){
String[] s = mEndDateSplit = mEndDate.split("/");
int mEndDay = Integer.parseInt(mEndDateSplit[0]);
int mEndMonth = Integer.parseInt(mEndDateSplit[1]);
int mEndYear = Integer.parseInt(mEndDateSplit[2]);
int mHour = Integer.parseInt(mTimeSplit[0]);
int mMinute = Integer.parseInt(mTimeSplit[1]);
Calendar mEndCalendar = Calendar.getInstance();
mEndCalendar.set(Calendar.MONTH, --mEndMonth);
mEndCalendar.set(Calendar.YEAR, mEndYear);
mEndCalendar.set(Calendar.DAY_OF_MONTH, mEndDay);
mEndCalendar.set(Calendar.HOUR_OF_DAY, mHour);
mEndCalendar.set(Calendar.MINUTE, mMinute);
mEndCalendar.set(Calendar.SECOND, 0);
String mRepeatNo = rm.getRepeatNo();
if (mRepeatType.equals("Daily")) {
mRepeatTime = Integer.parseInt(mRepeatNo) * milDay;
} else if (mRepeatType.equals("Every 2 Days")) {
mRepeatTime = Integer.parseInt(mRepeatNo) * milDay;
} else if (mRepeatType.equals("Every 3 Days")) {
mRepeatTime = Integer.parseInt(mRepeatNo) * milDay;
} else if (mRepeatType.equals("Weekly")) {
mRepeatTime = Integer.parseInt(mRepeatNo) * milWeek;
} else if (mRepeatType.equals("Monthly")) {
mRepeatTime = Integer.parseInt(mRepeatNo) * milMonth;
}
if(SystemClock.elapsedRealtime() + mRepeatTime > nEndCalendar.getTimeInMills()) {
// The next alert will happen after the end time, cancel it and delete it from the database.
cancelAlarm(context, mReceivedID);
rb.deleteReminder(mReceivedID);
}
}else{
// The alert isn't set to be repeated, cancel and delete it from the database.
cancelAlarm(context, mReceivedID);
rb.deleteReminder(mReceivedID);
}
}
}
I have created an events. I have given option for notification before 10 minutes, 30 minutes and before every hour till 12 hours before. I have to set notification for all these intervals.
Now I want to cancel the particular notification if the switch is off. I have given the same intent to cancel the notification. But I think all the notifications got cancelled.
Also I have created time tables and events are created using the time table's id. Now if I delete one time table I want to delete all the notifications set to the events that belongs to the deleted time table.
How can I do this?
Set notification time function:
public void setNotificationTime(Calendar c)
{
Date dateFrom = new Date();
df = new SimpleDateFormat("E MMM dd HH:mm:ss zzzz yyyy");
try {
dateFrom = df.parse(startTime);
}
catch (ParseException ex) {
}
dateFrom.getTime();
c.setTime(dateFrom);
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
if(notificationTime !=null && !notificationTime.isEmpty()) {
if (notificationTime.equals("10 Minutes Before")) {
c.set(Calendar.HOUR_OF_DAY, hour);
c.set(Calendar.MINUTE, minute - 10);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
c.set(Calendar.DATE, day);
// c.set(Calendar.DAY_OF_WEEK,);
SetDay(c);
notification = c.getTime();
notificationTime = df.format(notification);
setAlarm(c);
Toast.makeText(getApplicationContext(), notificationTime, Toast.LENGTH_SHORT).show();
} else if (notificationTime.equals("30 Minutes Before")) {
c.set(Calendar.HOUR_OF_DAY, hour);
c.set(Calendar.MINUTE, minute - 30);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
c.set(Calendar.DATE, day);
// c.set(Calendar.DAY_OF_WEEK,);
SetDay(c);
notification = c.getTime();
notificationTime = df.format(notification);
Toast.makeText(getApplicationContext(), notificationTime, Toast.LENGTH_SHORT).show();
setAlarm(c);
} else if (notificationTime.equals("1 Hour Before")) {
c.set(Calendar.HOUR_OF_DAY, hour - 1);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
c.set(Calendar.DATE, day);
// c.set(Calendar.DAY_OF_WEEK,);
SetDay(c);
notification = c.getTime();
notificationTime = df.format(notification);
Toast.makeText(getApplicationContext(), notificationTime, Toast.LENGTH_SHORT).show();
setAlarm(c);
}
Set Alarm function:
#SuppressLint("NewApi")
private void setAlarm(Calendar targetmCalen) {
intent = new Intent(getBaseContext(), NotificationReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 7, pendingIntent);
}
Notification cancel on switch off:
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
intent = new Intent(getApplicationContext(), NotificationReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), RQS_1, intent, 0);
alarmManager.cancel(pendingIntent);
Notification receiver:
public class NotificationReceiver extends BroadcastReceiver {
public static int MY_NOTIFICATION_ID = 0;
NotificationManager notificationManager;
Notification myNotification;
EventTableHelper db;
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Time is set", Toast.LENGTH_LONG).show();
db = new EventTableHelper(context);
List<EventData> testSavings = db.getAllEvents();
for (EventData ts : testSavings) {
String log = "from date:" + ts.getFromDate()
+ " ,to date: " + ts.getToDate()
+ " ,location: " + ts.getLocation()
+ " ,title " + ts.getTitle();
Calendar c = Calendar.getInstance();
Date date = new Date();
Date date1 = new Date();
Log.d("Result: ", log);
SimpleDateFormat df = new SimpleDateFormat("E MMM dd hh:mm:ss zzzz yyyy");
SimpleDateFormat df2 = new SimpleDateFormat("hh:mm a");
try {
date = df.parse(ts.getFromDate());
date1 = df.parse(ts.getToDate());
} catch (ParseException ex) {
}
String timeFrom = df2.format(date);
// String startTime = String.valueOf(timeFrom);
String timeTo = df2.format(date1);
// String endTime = String.valueOf(timeTo);
String location = ts.getLocation();
String title = ts.getTitle();
Intent myIntent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
context,
0,
myIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
if(location.equals(""))
{
String msg = "From : " + timeFrom + "\nTo : " + timeTo;
myNotification = new NotificationCompat.Builder(context)
.setContentTitle("Event : " + title)
.setContentText(msg)
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setSmallIcon(R.drawable.eventicon)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setDefaults(Notification.DEFAULT_SOUND)
.build();
}
else
{
String msg = "From : " + timeFrom + "\nTo : " + timeTo + "\nAt : " + location;
myNotification = new NotificationCompat.Builder(context)
.setContentTitle("Event : " + title)
.setContentText(msg)
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setSmallIcon(R.drawable.eventicon)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setDefaults(Notification.DEFAULT_SOUND)
.build();
}
Log.i("Notify", "Notification");
notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
myNotification.flags=Notification.FLAG_AUTO_CANCEL;
Intent i = new Intent();
i.putExtra("notificationId",MY_NOTIFICATION_ID);
MY_NOTIFICATION_ID ++;
}
}
}
Which changes should I do to achieve the desired result?
you need to create different pending intents and then use particular pending intent to cancel specific alarm .Create your pending intent as usual but add the different flag for different alarm.
pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, FLAG);//Set different value of Flag at the time creating alarm
So to make it generic just add one more params in your
setAlarm(Calendar targetmCalen,int flag)
I have used time picker to set the time of notification by user. I have used alarm manager and notification builder.
I have called the setAlarm method on clickListener of a button to save data. So when this setAlarm method gets called Notification raises at the same time as well as it raises at the time user have set.
I don't want it to be raised when I save the data.
Can anyone tell why this is happening?
setAlarm method
#SuppressLint("NewApi")
private void setAlarm(Calendar targetmCalen) {
AlarmManager alarmMgr;
PendingIntent alarmIntent;
alarmMgr = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), NotificationReceiver.class);
alarmIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
Toast.makeText(getBaseContext(),
"call alarmManager.setExact()",
Toast.LENGTH_LONG).show();
intent.putExtra("title",eventTitle);
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, targetmCalen.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent);
ComponentName receiver = new ComponentName(getApplicationContext(),NotificationReceiver.class);
PackageManager pm = getApplicationContext().getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
}
NotificationReceiver
public class NotificationReceiver extends BroadcastReceiver {
private static final int MY_NOTIFICATION_ID = 0;
NotificationManager notificationManager;
Notification myNotification;
EventTableHelper db;
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Time is set", Toast.LENGTH_LONG).show();
db = new EventTableHelper(context);
List<EventData> testSavings = db.getAllEvents();
for (EventData ts : testSavings) {
String log = "from date:" + ts.getFromDate()
+ " ,to date: " + ts.getToDate()
+ " ,location: " + ts.getLocation()
+ " ,title " + ts.getTitle();
Date date = new Date();
Date date1 = new Date();
Log.d("Result: ", log);
SimpleDateFormat df = new SimpleDateFormat("E MMM dd HH:mm:ss zzzz yyyy");
SimpleDateFormat df2 = new SimpleDateFormat("HH:mm a");
try {
date = df.parse(ts.getFromDate());
date1 = df.parse(ts.getToDate());
} catch (ParseException ex) {
}
String timeFrom = df2.format(date);
String startTime = String.valueOf(timeFrom);
String timeTo = df2.format(date1);
String endTime = String.valueOf(timeTo);
String location = ts.getLocation();
String title = ts.getTitle();
Intent myIntent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
context,
0,
myIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
if(location.equals(""))
{
String msg = "From : " + startTime + "\nTo : " + endTime;
myNotification = new NotificationCompat.Builder(context)
.setContentTitle("Event : " + title)
.setContentText(msg)
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setSmallIcon(R.drawable.eventicon)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setDefaults(Notification.DEFAULT_SOUND)
.build();
}
else
{
String msg = "From : " + startTime + "\nTo : " + endTime + "\nAt : " + location;
myNotification = new NotificationCompat.Builder(context)
.setContentTitle("Event : " + title)
.setContentText(msg)
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setSmallIcon(R.drawable.eventicon)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setDefaults(Notification.DEFAULT_SOUND)
.build();
}
Log.i("Notify", "Notification");
notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
}
}
}
EDIT:
Calendar object Passed in setAlarm method
c.set(Calendar.HOUR_OF_DAY, hour);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND,0);
c.set(Calendar.MILLISECOND,0);
c.set(Calendar.DATE, day);
c.set(Calendar.DAY_OF_WEEK,2);
notification = c.getTime();
notificationTime = df.format(notification);
Toast.makeText(getApplicationContext(),notificationTime,Toast.LENGTH_SHORT).show();
Thank you..
I am getting null values in service class :-
if (intent != null && intent.getAction() != null) {
matchName = intent.getStringExtra("match");
matchDate = intent.getStringExtra("time");
Log.d(" Service Match ", intent.getExtras().toString());
}
//onCreate Code
#Override
protected void onCreate(Bundle savedInstanceState) {
Button match1 = (Button) findViewById(R.id.match1);
match1.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Calendar endTime = Calendar.getInstance();
SimpleDateFormat inputFormat = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss a");
inputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat nativeFormat = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss a");
nativeFormat.setTimeZone(TimeZone.getDefault());
SimpleDateFormat nativeFormat1 = new SimpleDateFormat(
"yyyy-MM-dd hh:mm a");
String inpt = matchTimeInGMT(v); // "2014-03-22 8:45:00 PM";
Button matchButton = (Button) v;
String matchName = "ABC vs DEF";
try {
inptdate = inputFormat.parse(inpt);
date2 = nativeFormat.format(inptdate);
endTime.setTime(nativeFormat.parse(date2));
// endTime.add(Calendar.HOUR_OF_DAY, 3);
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", endTime.getTimeInMillis());
intent.putExtra("allDay", false);
intent.putExtra("rrule", "FREQ=YEARLY;COUNT=1");
intent.putExtra("endTime", endTime.getTimeInMillis());
intent.putExtra("title", matchName);
startActivity(intent);
Calendar cal = Calendar.getInstance();
cal.setTime(endTime.getTime());
Intent svc = new Intent(this,MyAlarmService.class);
svc.setAction("matchTime");
svc.putExtra("match", matchName.toString());
svc.putExtra("time", nativeFormat1.format(cal.getTime()).toString());
startService(svc);
PendingIntent alarmIntent;
Intent myIntent1 = new Intent(FIXTURE.this, MyReceiver.class);
alarmIntent = PendingIntent.getBroadcast(FIXTURE.this, 0,
myIntent1, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, endTime.getTimeInMillis(),
alarmIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
Log output -Bundle[{time=2014-03-25 12:20 AM, match=ABC Vs DEF}]
I am getting values for match and time but not getting assigned to matchName and matchDate variables. Please help.