How to set multiple notification using a unique ID? - android

I trying to put notification for my todo list. The notification works, but for only 1 item, how do I set for multiple notifications. If I put two items for notification, only the last one that I set will show up a notification. Here is my code for the alarm task.
public class AlarmTask implements Runnable{
// The date selected for the alarm
private final Calendar date;
// The android system alarm manager
private final AlarmManager am;
// Your context to retrieve the alarm manager from
private final Context context;
public AlarmTask(Context context, Calendar date) {
this.context = context;
this.am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
this.date = date;
}
#Override
public void run() {
// Request to start service when the alarm date is upon us
// We don't start an activity as we just want to pop up a notification into the system bar not a full activity
Intent intent = new Intent(context, NotifyService.class);
intent.putExtra(NotifyService.INTENT_NOTIFY, true);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
// Sets an alarm - note this alarm will be lost if the phone is turned off and on again
am.set(AlarmManager.RTC, date.getTimeInMillis(), pendingIntent);
}
}

Related

Android: How to stop repeating alarm without unsetting the alarm itself

I have an Android app where I need to trigger reminders everyday at the same time. The alarm must repeat every 5 minutes if ignored. If the user declares he read the reminder, by clicking an OK button, the alarm must stop repeating, until it is triggered the day after.
So, I want the alarm to stop repeating after the user's confirmation, and I read that with AlarmManager I should use the cancel() method. But I don't want to delete the alarm for future days, I just want it to stop repeating until next trigger.
In other words, I don't want the cancel() method to unset the alarm for the future days. Is it the default behavior of the cancel() method or do I have to cancel the alarm and then re-set it every time?
This is my code for setting the alarm:
public class AlarmSettingManager
{
private static Context context;
// Constructor
public AlarmSettingManager(Context c)
{
context = c;
}
private static class PrescriptionAlarmSetter extends AsyncTask<String, Void, Boolean>
{
SharedPrefManager sharedPrefManager = SharedPrefManager.getInstance(context);
#Override
protected Boolean doInBackground(String... strings)
{
// Get the list of prescriptions from SharedPreferences
if(!sharedPrefManager.getPrescrizioneList().equals(""))
{
try
{
JSONArray responseJsonArray = new JSONArray(sharedPrefManager.getPrescrizioneList());
int currentID = Constants.PRESCRIZIONE_ALARM_ID;
for(int j=0; j<responseJsonArray.length(); j++)
{
JSONObject singlePrescription = responseJsonArray.getJSONObject(j);
Prescrizione prescrizione = new Prescrizione
(
singlePrescription.getInt("id_prescrizione"),
singlePrescription.getInt("id_medico"),
singlePrescription.getInt("id_farmaco"),
singlePrescription.getInt("numero_pasticche"),
singlePrescription.getInt("totale_compresse"),
singlePrescription.getString("nome"),
singlePrescription.getString("ora_assunzione"),
singlePrescription.getString("posologia"),
singlePrescription.getString("suggerimenti")
);
// Start setting the alarm for current prescription
Intent alarmIntent = new Intent(context, AlarmBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast
(
context.getApplicationContext(),
currentID,
alarmIntent,
PendingIntent.FLAG_CANCEL_CURRENT
);
// put the RequestCode ID as extra in order to identify which alarm is triggered
alarmIntent.putExtra("id", currentID);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
// Specify the time to trigger the alarm
calendar.set(Calendar.HOUR_OF_DAY, prescrizione.getIntHour());
calendar.set(Calendar.MINUTE, prescrizione.getIntMinutes());
calendar.set(Calendar.SECOND, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// Set the time interval (in milliseconds) to repeat the alarm if the previous one was ignored
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 300000L, pendingIntent);
currentID++;
}
}
catch(JSONException e)
{
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Boolean b)
{
super.onPostExecute(b);
}
}
public boolean setAlarms()
{
AlarmSettingManager.PrescriptionAlarmSetter prescriptionAlarmSetter = new AlarmSettingManager.PrescriptionAlarmSetter();
prescriptionAlarmSetter.execute();
return true;
}
}
And this is the piece of code I'm going to adapt in order to cancel the alarm repeating:
Intent alarmIntent = new Intent(context, AlarmBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast
(
context.getApplicationContext(),
currentID,
alarmIntent,
0
);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
Thanks.
At the time of cancelling alarm schedule a new alarm for the next day.
The intention of the "cancel" option is to remove the alarm.
Your application should add a new alarm just as the original was setup.
You can find a nice example of implementing a full alarm in Android at the following link, including how to re-add it on device reboot.
Repeat Alarm Example In Android Using AlarmManager

How to create alerts using alarm manager and background service call and a web service call inside background service?

I could not explain my problem in the Title..Here's the detailed explanation of my problem :
I have an application where arrival time of trains are displayed.
I want to add a feature where User can create an alert if the train is 10-5 minutes away from station.
A form is displayed to create an alert (all the values are stored in DB).
alertID = db.insert_alerts(name,starttime,endtime,booleanrepeat);
I am using alarm manager to create the notification :
if (is_repeat.equals("true")) {
new AlertsReceiver().setRepeatAlarm(getApplicationContext(), mCalendar, (int)alertID ,10000);
} else if (is_repeat.equals("false")) {
new AlertsReceiver().setAlarm(getApplicationContext(), mCalendar,(int)alertID);
}
below is the Receiver class :
public class AlertsReceiver extends WakefulBroadcastReceiver {
private int alertId;
AlarmManager mAlarmManager;
PendingIntent mPendingIntent;
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if(extras == null) {
Log.d("Service","null");
} else {
alertId= extras.getInt("alertId");
}
Intent intent1 = new Intent(context,MService.class);
intent1.putExtra("alertId", alertId);
context.startService(intent1);
}
public void setAlarm(Context context, Calendar calendar, int ID) {
mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context,AlertsReceiver.class);
intent.putExtra("alertId", 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);
}
public void setRepeatAlarm(Context context, Calendar calendar, int ID, long RepeatTime) {
mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Log.e("asetRepeat",ID+"");
Intent intent = new Intent(context, AlertsReceiver.class);
intent.putExtra("alertId", 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;
// Start alarm using initial notification time and repeat interval time
mAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + diffTime,
RepeatTime , mPendingIntent);
}
public void cancelAlarm(Context context, int ID) {
mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Toast.makeText(context,"Cancelled"+ID,Toast.LENGTH_LONG).show();
// Cancel Alarm using Reminder ID
mPendingIntent = PendingIntent.getBroadcast(context, ID, new Intent(context, RiderAlertsReceiver.class), 0);
mAlarmManager.cancel(mPendingIntent);
}
}
In receiver I am starting a service where I am making a webservice call :
Once an alarm manager is set..A webservice call is made in background service to check the minutes in which train will arrive :
if the minutes < 10 minutes notification is displayed else the webservice call should run again
So, i place the webservice in timer which runs every 1 minute.
The issue is how to stop the timer once the notification is received.
Also, the every time the receiver is starting the same service so only one alert is working at one time.
The user can create multiple alerts and all alerts are stored in DB.
Please can any one tell me the best way to implement this feature.
Appreciate Help...!

How to Create a Distinct PendingIntents

I have an app that allows a user to create a reminder to alert them in the future. The issue I am running into, is that as a user creates more than one reminder, the pending intent only triggers on the latest one created, with the earliest reminder content to display, ie:
Task 1, set for 4pm
Task 2, set for 5pm
Task 3, set for 6pm
No reminder will appear until 6pm, which will display Task 1.
I believe it has to due with the lack of uniqueness of the PendingIntent:
public class ReminderManager {
private Context mContext;
private AlarmManager mAlarmManager;
public ReminderManager(Context context) {
mContext = context;
mAlarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
}
public void setReminder(Long taskId, Calendar when) {
Intent i = new Intent(mContext, OnAlarmReceiver.class);
i.putExtra(RemindersDbAdapter.KEY_ROWID, (long)taskId);
PendingIntent pi = PendingIntent.getBroadcast(mContext, 0, i, PendingIntent.FLAG_ONE_SHOT);
mAlarmManager.set(AlarmManager.RTC_WAKEUP, when.getTimeInMillis(), pi);
}
}
How can I ensure that each reminder is unique and gets its correct time on time?
You need to provide something other than 0 for the requestCode param. Try making it a unique ID for each request.

Cancel an AlarmManager pendingIntent in another pendingintent

I want cancel AlarmManager which define a service,in this service might start a new AlarmManger or cancel alarm that defined before.And I know the params pendingintent in alarmManager.cancel(PendingIntent),must be the same.compare with filterEquals(Intent other)
but It still not work.cancel failed.
here is my code
public class GetRoundStroe {
private Store[] stores;
private Context mContext;
public GetRoundStroe(Context mContext) {
this.mContext = mContext;
}
public Store[] getStores() {
if (ComCommand.haveInternet(mContext)) {
start_am_normal();
} else {
start_am_silence();
}
return stores;
}
public Store[] start_am_silence() {
long firstTime = SystemClock.elapsedRealtime();
AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
if (AlarmHolder.mAlarmNormal != null) {
am.cancel(AlarmHolder.mAlarmNormal);
}
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
firstTime, TestSwitch.getInstance().getSilence_time(), AlarmHolder.mAlarmSilence);
return null;
}
public Store[] start_am_normal() {
long firstTime = SystemClock.elapsedRealtime();
AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
if (AlarmHolder.mAlarmSilence != null) {
MyLog.e(GetRoundStroe.class,"AlarmHolder.mAlarmSilence"+AlarmHolder.mAlarmSilence+"");
am.cancel(AlarmHolder.mAlarmSilence);
}
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
firstTime, TestSwitch.getInstance().getNormal_time(), AlarmHolder.mAlarmNormal);
return null;
}
private static final class AlarmHolder {
static final PendingIntent mAlarmSilence = PendingIntent.getService(ApplicationContext.getInstance(),
0,
new Intent(ApplicationContext.getInstance(), GetRoundSilenceService.class),
0);
static final PendingIntent mAlarmNormal = PendingIntent.getService(ApplicationContext.getInstance(),
0, new
Intent(ApplicationContext.getInstance(), GetRoundNormalService.class),
0);
}
}
GetRoundSilenceService and GerRoundNormalService invoke start_am_normal() or start_am_silence; Anyone could help me? thanks
myIntent = new Intent(SetActivity.this, AlarmActivity.class);
pendingIntent = PendingIntent.getActivity(CellManageAddShowActivity.this,
id, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
pendingIntent.cancel();
alarmManager.cancel(pendingIntent);
These lines of code surely can help you remove/cancel the pending intent and alarm.
The main thing that you will need is:
Create pending intent with the same id and appropriate intent FLAG.
Cancel that pending intent.
Cancel the alarm using alarm manager.
#MKJParekh answer is correct, however I would like to add more information so that we all know what will work and what will not.
Lets say on activityA you create and set the AlarmManager to open activityC in 30 seconds, then on some other activity which can be any, we want to cancel that AlarmManager. Thus, we would do the following;
in activityA we create and set the AlarmManager;
//activityA
Intent myIntentA = new Intent(actvityA.this, activityB.class)
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent myPendingIntent = PendingIntent.getActivity(activityA.this, 0, myIntentA, PendingIntent.FLAG_ONE_SHOT);
//Calendar with the time we want to fire the Alarm
Calendar calendar = Calendar.getInstance(); // Get Current Time
calendar.add(Calendar.SECOND,30); //Fire Alarm in 30 seconds from Now.
((AlarmManager)getSystemService(ALARM_SERVICE)).setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), myPendingIntent);
in Another Activity some time later we want to cancel such AlarmManager created in activityA which we have no access to. Lets call this current activity activityZ;
//activityZ
Intent myIntentZ = new Intent(activityZ.this, activityB.class);
PendingIntent pendingIntentZ = PendingIntent.getActivity(activityZ.this, 0, myIntentZ, PendingIntent.FLAG_ONE_SHOT);
((AlarmManager)getSystemService(ALARM_SERVICE)).cancel(pendingIntentZ);
Some important points,
The context we provide in activityA in new Intent(context) and getActivity(context) are the same, however they do not have to match the activity from where we are canceling the AlarmManager, in this case activityZ has another context.
The class we want to open with the AlarmManager has to be the same in both activities new Intent (context, activityB.class), the requestCode which is an int must be the same, I used 0 for this example. Finally the flag has to be the same in both activities PendingIntent.FLAG_ONE_SHOT.
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); was used because PendingIntent.getActivity requires it if we are starting an activity outside of a context of an existing activity.

How to cancel an alarm in android?

I am trying to cancel all alarms other an intent
i am sending stuff in using
new gofile(this).setSilent(mRowId, mCalendar);
that then goes to gofile
public class gofile {
private Context goon
private AlarmManager alarm;
public gofile(Context goon){
mContext = context;
alarm = (AlarmManager)goon.getSystemService(Context.ALARM_SERVICE);
}
public void setSilent(Long Id, Calendar when){
Intent i = new Intent(gon, anohterclass.class);
PendingIntent go = PendingIntent.getBroadcast(goon, 0 , i, PendingIntent.FLAG_ONE_SHOT);
alarm.set(AlarmManager.RTC_WAKEUP, when.getTimeInMillis(), go);
how would i cancel the alarms from another file?
You must use the cancel method, and you must make sure the PendingIntent contains the information than the one you used to set the alarm.

Categories

Resources