in my program i set notifications with a string and its clock to get a notification with that string at its clock.(I mean user wants to get a notification with a string at demanding time, and user gave me a lot of strings and their clocks.) And if the user want to cancel that notification i don't know how to do it.
I tried alarmManager.cancel(pendingIntent) but I want to cancel the only one notification not all of them. Also, it doesn't cancel any notification too.
here is the code in the main
public void gecikmeliGoster(String plan, int yil, int ay, int gun, String saat){
NotificationCompat.Builder builder;
NotificationManager bildirimYoneticisi = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent ıntent = new Intent(HatirlaticiKur.this, AlarmReciever.class);
PendingIntent gidilecekIntent = PendingIntent.getActivity(this, 1, ıntent, PendingIntent.FLAG_UPDATE_CURRENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String kanalId = "kanalId";
String kanalAd = "kanalAd";
String kanalTanım = "kanalTanım";
int kanalOnceligi = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel kanal = bildirimYoneticisi.getNotificationChannel(kanalId);
if (kanal == null) {
kanal = new NotificationChannel(kanalId, kanalAd, kanalOnceligi);
kanal.setDescription(kanalTanım);
bildirimYoneticisi.createNotificationChannel(kanal);
}
builder = new NotificationCompat.Builder(this, kanalId);
builder.setContentTitle("Hatırlatıcı")
.setContentText(plan)
.setSmallIcon(R.drawable.hatirlatici)
.setAutoCancel(true)
.setContentIntent(gidilecekIntent);
} else {
builder = new NotificationCompat.Builder(this);
builder.setContentTitle("Hatırlatıcı")
.setContentText(plan)
.setSmallIcon(R.drawable.hatirlatici)
.setContentIntent(gidilecekIntent)
.setAutoCancel(true)
.setPriority(Notification.PRIORITY_HIGH);
}
Intent broadcastIntent = new Intent(HatirlaticiKur.this, AlarmReciever.class);
broadcastIntent.putExtra("nesne", builder.build());
PendingIntent gidilecekBroadcast = PendingIntent.getBroadcast(this, 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//long gecikme = SystemClock.elapsedRealtime() + 5000; //bu 5 saniyede bir bildirim gelmesi için falan
String[] noktasiz = saat.split(":");
int akrep = Integer.parseInt(noktasiz[0]);
int yelkovan = Integer.parseInt(noktasiz[1]);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.YEAR, yil);
calendar.set(Calendar.MONTH, ay);
calendar.set(Calendar.DATE, gun);
calendar.set(Calendar.HOUR_OF_DAY, akrep);
calendar.set(Calendar.MINUTE, yelkovan);
calendar.set(Calendar.SECOND, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 0, gidilecekBroadcast);
}
and here is the code in AlarmReceiver
public class AlarmReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager bildirimYoneticisi = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification bildirim = intent.getParcelableExtra("nesne");
bildirimYoneticisi.notify(1,bildirim);
}
}
I want to cancel demanding notifications, i will appreciate your help
use used 0 id for setting alarm
PendingIntent gidilecekBroadcast = PendingIntent.getBroadcast(this, 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
You need uniqueid for all notification set using alarmmanager
then based on uniqueid you can cancel alarm
PendingIntent gidilecekBroadcast =
PendingIntent.getBroadcast(getApplicationContext(), uniqueid , broadcastIntent,
PendingIntent.FLAG_UPDATE_CURRENT)
alarmManager.cancel(gidilecekBroadcast);
Related
I have a problem with notifications in my app. I want to set multiple notifications for different hours of the day. For example, let's take 8, 12 and 23 o'clock. But only the one at 23 o'clock triggers every day. What's wrong with my code and will it work even if the app is killed?
Here's the code that sets alarms in my activity
public void myAlarm(int hour, int minute) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);
Intent intent = new Intent(getApplicationContext(), Reminder.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
if (alarmManager != null) {
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
}
and this is what I wrote in onCreate
myAlarm(8, 0);
myAlarm(12, 0);
myAlarm(23, 0);
this is my receiver
public class Reminder extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent in = new Intent(context, MySecoundActivity.class);
in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, in, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "Reminder")
.setSmallIcon(R.drawable.bell)
.setContentTitle("Notification!")
.setContentText("Text of notification")
.setColor(0xfb3ff)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_HIGH);
NotificationManagerCompat notificationMngr = NotificationManagerCompat.from(context);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Reminder";
String description = "reminder channel";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel("Reminder", name, importance);
channel.setDescription(description);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
}
notificationMngr.notify(200, builder.build());
}
Receiver is in android manifest
<receiver android:name=".Reminder"/>
This is the expected behavior since in your code, when you set the alarm, you have to give every PendingIntent unique requestCode which in your case remains the same, i.e., 0. So when you set another alarm with same requestCode, the last alarm gets updated to the new time instead of creating a new alarm. So only your last alarm works. So at the time of setting the alarm, in your PendingIntent.getBroadcast(), instead of the 0, you could use either the Random class to generate a random number every time or you could just use (int)System.currentTimeMillis() which would always be a different number.
I am able to get notifications at a particular time in future by using Calendar class java (Example 9:15am). The Alarm manager sends the broadcast to the broadcast receiver whenever the time is 9:15am but when I open the app after 9:15am (Example 9:20am). I receive the same notification. Can anyone help my about this.
My Manifest
<receiver android:name=".others.NotificationReceiver"/>
Notification Receiver.java
public class NotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
createNotification(context);
}
private void createNotification(Context context) {
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
NotificationChannel linkChannel = new NotificationChannel(link_channel_id, "Link Channel", NotificationManager.IMPORTANCE_HIGH);
linkChannel.setDescription("This channel is used to show Zoom Links");
notificationManager.createNotificationChannel(linkChannel);
}
Notification notification = new NotificationCompat.Builder(context, link_channel_id)
.setSmallIcon(R.mipmap.ic_launcher_foreground)
.setContentTitle("Test Notification")
.setContentText("This is a test notification")
.setPriority(NotificationCompat.PRIORITY_MAX)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.build();
notificationManager.notify(1, notification);
}
}
My Alarm Manager
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 10);
calendar.set(Calendar.SECOND, 0);
Intent myIntent1 = new Intent(this, NotificationReceiver.class);
myIntent1.setAction(ACTION_ONE);
PendingIntent pendingIntent1 = PendingIntent.getBroadcast(this, 1, myIntent1, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent1);
I've set an Alarm in my app to trigger a notification every X minutes. The first time works, but then is not repeating.
The API I'm working on is API 18 (Android 4.3).
MainActivity.class
public void setAlarm(Consumo con){
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
int id = (int) con.getId();
calendar.add(Calendar.MINUTE, con.getTime());
Intent notification = new Intent(MainActivity.this, AlarmReceiver.class);
notification.putExtra("cadena", con.getName()+
" "+con.getQuantity()+" "+ con.getType()+" "+con.getPills()+" comprimidos");
notification.putExtra("id", id);
PendingIntent pendingNotif = PendingIntent.getBroadcast(MainActivity.this,
id, notification, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), calendar.getTimeInMillis(), pendingNotif);
}
AlarmReceiver.class
public class AlarmReceiver extends BroadcastReceiver {
private static String CHANNEL_ID = "medicinas.android.unex.cum.es.app";
#Override
public void onReceive(Context context, Intent intent) {
Intent notificationIntent = new Intent(context, NotificationActivity.class);
Bundle b = intent.getExtras();
int id = b.getInt("id");
notificationIntent.putExtra("id", id);
TaskStackBuilder tsb = TaskStackBuilder.create(context);
tsb.addParentStack(NotificationActivity.class);
tsb.addNextIntent(notificationIntent);
Intent tomada = new Intent(context, NotificationActivity.class);
tomada.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
tomada.putExtra("id", id);
PendingIntent pTomada = PendingIntent.getActivity(context, 155, tomada, PendingIntent.FLAG_ONE_SHOT);
PendingIntent pendingIntent = tsb.getPendingIntent(id, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(context);
Notification notification = builder.setContentTitle("Control de Medicinas")
.setContentText(intent.getExtras().getString("cadena"))
.setTicker("¡Hora de tomar la medicina")
.setSmallIcon(R.mipmap.ic_launcher)
.addAction(android.R.drawable.btn_default, "Medicina tomada", pTomada)
.setContentIntent(pendingIntent).build();
notification.defaults = Notification.DEFAULT_SOUND;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setChannelId(CHANNEL_ID);
}
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"MedicinaNotificacion",
NotificationManager.IMPORTANCE_DEFAULT
);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(id, notification);
}
}
RECEIVER AFTER MODIFICATIONS
public class AlarmReceiver extends BroadcastReceiver {
private static String CHANNEL_ID = "medicinas.android.unex.cum.es.app";
private Context mContext;
#Override
public void onReceive(Context context, Intent intent) {
Intent notificationIntent = new Intent(context, NotificationActivity.class);
Bundle b = intent.getExtras();
mContext = context;
int id = b.getInt("id");
notificationIntent.putExtra("id", id);
Consumo con = new Consumo(id, b.getString("name"), b.getInt("quantity"),
b.getString("type"), b.getInt("pills"), true, b.getInt("time"));
TaskStackBuilder tsb = TaskStackBuilder.create(context);
tsb.addParentStack(NotificationActivity.class);
tsb.addNextIntent(notificationIntent);
Intent tomada = new Intent(context, NotificationActivity.class);
tomada.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
tomada.putExtra("id", id);
String cadena = b.getString("name")+
" "+b.getInt("quantity")+" "+
b.getString("type")+" "+b.getInt("pills")+" comprimidos";
PendingIntent pTomada = PendingIntent.getActivity(context, 155, tomada, PendingIntent.FLAG_ONE_SHOT);
PendingIntent pendingIntent = tsb.getPendingIntent(id, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(context);
Notification notification = builder.setContentTitle("Control de Medicinas")
.setContentText(cadena)
.setTicker("¡Hora de tomar la medicina")
.setSmallIcon(R.mipmap.ic_launcher)
.addAction(android.R.drawable.btn_default, "Medicina tomada", pTomada)
.setContentIntent(pendingIntent).build();
notification.defaults = Notification.DEFAULT_SOUND;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setChannelId(CHANNEL_ID);
}
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"MedicinaNotificacion",
NotificationManager.IMPORTANCE_DEFAULT
);
notificationManager.createNotificationChannel(channel);
}
setAlarm(con);
notificationManager.notify(id, notification);
}
public void setAlarm(Consumo con){
AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
int id = (int) con.getId();
calendar.add(Calendar.MINUTE, con.getTime());
Intent notification = new Intent(mContext , AlarmReceiver.class);
notification.putExtra("cadena", con.getName()+
" "+con.getQuantity()+" "+ con.getType()+" "+con.getPills()+" comprimidos");
notification.putExtra("id", id);
notification.putExtra("name", con.getName());
notification.putExtra("quantity", con.getQuantity());
notification.putExtra("type", con.getType());
notification.putExtra("pills", con.getPills());
notification.putExtra("time", con.getTime());
Log.i("DEBUG RECEIVER: ", ""+con.getTime());
PendingIntent pendingNotif = PendingIntent.getBroadcast(mContext,
id, notification, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, con.getTime()*60*1000, pendingNotif);
}
}
If you need more of the code tell me, I'll add it quickly.
Thanks in advance.
try:
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), calendar.getTimeInMillis(), pendingNotif);
and then in onReceive(), call setAlarm() method to set the next alarm
I think issue is in this line :
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), calendar.getTimeInMillis(), pendingNotif);
Let's assume you want alarm to go off after every 2 minutes, it should be :
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 2*60*1000, pendingNotif);
In the above example, replace 2 with whatever minute you want the alarm to go off.
I start to combine alarm manager and notification manager on android, and this is my code:
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setReminderAlarm();
}
public void setReminderAlarm() {
Intent intent = new Intent(MainActivity.this, ReminderReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, ReminderReceiver.NOTIF_ID, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 6);
calendar.set(Calendar.MINUTE, 59);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 86400000L, pendingIntent);
}
ReminderReceiver.java
public static int NOTIF_ID = 101;
#Override
public void onReceive(Context context, Intent intent) {
showAlarmNotification(context);
}
public void showAlarmNotification(Context context) {
Intent intentClick = new Intent(context, MainActivity.class);
PendingIntent pendingClick = PendingIntent.getActivity(context, 0, intentClick, 0);
NotificationManager notificationManagerCompat = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.cinema)
.setContentTitle(title)
.setContentIntent(pendingClick)
.setContentText(message)
.setColor(ContextCompat.getColor(context, android.R.color.transparent))
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
.setSound(alarmSound)
.setAutoCancel(true);
notificationManagerCompat.notify(NOTIF_ID, builder.build());
}
Every time I run the application, the notification always appears even though I have set the time. How do I prevent that?
Thank you.
The issue is you are setting the time to current day. So if you are opening your app after 6:00, your alarm manager will immediately fire.
You need to check whether the time is over 6:00 for the current day, if yes you need to change the date to the next day:
public void setReminderAlarm() {
Intent intent = new Intent(MainActivity.this, ReminderReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, ReminderReceiver.NOTIF_ID, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
int curHr = calendar.get(Calendar.HOUR_OF_DAY);
// Checking whether current hour is over 6
if (curHr >= 6)
{
// Since current hour is over 6, setting the date to the next day
calendar.add(Calendar.DATE, 1);
}
calendar.set(Calendar.HOUR_OF_DAY, 6);
calendar.set(Calendar.MINUTE, 59);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 86400000L, pendingIntent);
}
I'm using the AlarmManager to fire a notification daily in specific time which is selected via time picker. The notification fired correctly in the same day but doesn't repeat correctly every day!!!
This is the method for setting the notification using setRepeating():
public void witer_reminder(View view)
{
am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, Witer_Notification.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
Calendar calSet = (Calendar) cal.clone();
calSet.set(Calendar.HOUR_OF_DAY, picker.getCurrentHour());
calSet.set(Calendar.MINUTE, picker.getCurrentMinute());
calSet.set(Calendar.SECOND, 0);
calSet.set(Calendar.MILLISECOND, 0);
if(calSet.compareTo(cal) <= 0)
{
// Today Set time passed, count to tomorrow
calSet.add(Calendar.DATE, 1);
}
am.setRepeating(AlarmManager.RTC_WAKEUP, calSet.getTimeInMillis(),
24 * 60 * 60 * 1000, pendingIntent);
}
and this is the BroadcastReciver class:
public class Witer_Notification extends BroadcastReceiver
{
NotificationManager nm;
#Override
public void onReceive(Context context, Intent intent)
{
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MainActivity.class), 0);
PendingIntent actiontIntent = PendingIntent.getActivity(context, 0,
new Intent(context, Suggestion.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("")
.setStyle(new NotificationCompat.BigTextStyle().bigText(""));
mBuilder.setContentIntent(contentIntent);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
// mBuilder.setStyle(new NotificationCompat.InboxStyle());
NotificationManager mNotificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
BTW, the application target is SDK 19.
I found that the setExact() replacing to set()
Correct.
it's not applicable for intervalAtMilis as a parameter
Not directly. But, when you get control in your BroadcastReceiver from the setExact() event, call setExact() again to schedule the next event.
I didn't find anything for setRepeating()
There is no simple solution, because Google is trying to point out to you that this is bad for the battery. Using setExact() as described above is your only option for exact repeating.