I would like to send a notification at a specific time. Below is my code. Right now, I only get a notification when I start the app, but I do not get a notification at the specified time. Could you help me understand what I am doing wrong.
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("My notification")
.setContentText("Trainieren sie jetzt!")
.setAutoCancel(true);
Intent resultIntent = new Intent(this, MainActivity2.class);
AlarmManager alarmManager =(AlarmManager)getSystemService(ALARM_SERVICE);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, 54);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 24*60*60*1000, resultPendingIntent);
mBuilder.setContentIntent(resultPendingIntent);
int mNotificationId = 001;
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
Thanks for helping!
You need to add:
#Override
public void onReceive(Context context, Intent intent) {
// Toast.makeText(MainActivity.con, "Hello from alarm", 1).show();
// System.out.println("Hello from Alarm");
context.startService(new Intent(context, NotificationService.class));
}
In the above example I am directing the process to my Service class to process my notification, managing wake locks and background service implementation. If you are not implementing a Service you can just display your notifications in the onRecieve method.
Please have a look here it has a complete implementation of the Alarm Class.
Related
I'm trying to do a simple Alarm manager, and although I'm adding a delay of 5 second,
the alarm in my phone goes off immediately.
I'm aware that in my receiver the alarm says to go off now,
but I understood that you set the delay to when you want it to go off at the pending intent.
what am I doing wrong ?
here is my alarm intent:
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent (AlarmClockScreen.this, AlarmNotificationReciever.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
manager.set(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime()+5000,pendingIntent);
and here is my Receiver
public class AlarmNotificationReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(android.R.mipmap.sym_def_app_icon)
.setContentTitle("Alarm TITLE")
.setContentText("I will finish, What you started")
.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)
.setContentInfo("Info");
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1,builder.build());
}
}
fixed it by adding
Calendar time = Calendar.getInstance();
time.setTimeInMillis(System.currentTimeMillis());
time.add(Calendar.SECOND, 30);
and then using time.getTimeInMillis()
Well I have tried enough to look for the answer to the question mentioned above, but my efforts have been futile so far.
I have created an alarm with the help of the alarmmanager class which will fire up the notification at regular intervals of time(probably about 5 days).
Below is the code for the implementation of the alarm happening inside onClick() of a button.
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
notificationIntent.addCategory("android.intent.category.DEFAULT");
PendingIntent broadcast = PendingIntent.getBroadcast(this, 100, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar cal = Calendar.getInstance();
if(fromDateEtxt.getText().toString().length()>0) {
cal.add(Calendar.HOUR_OF_DAY, 10);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(), 5 * 24 * 60 * 60 * 1000, broadcast);
}
The code for the broadcast receiver.
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent notificationIntent = new Intent(context, NotificationActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(NotificationActivity.class);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
Notification notification = builder.setContentTitle("Demo App Notification")
.setContentText("New Notification From Demo App..")
.setTicker("New Message Alert!")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent).build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
}}
The onClick() method apart from starting of the alarm changes the activity also. Now the problem I am facing is I dont know really how to stop the repeating alarm. I want to stop the alarm on a particular date. Secondly, I was confused whether to use the alarm.cancel for cancelling the alarm or to use another alarm for cancellation of the previous alarm as shown here. Apart from this, I wanted to know if the alarm could be cancelled from another activity or does the point seems unnecessary and the limit to the date could be set beforehand?
Hi I am new to notifications,
I wrote this code for notifications.
PendingIntent pendingIntent = PendingIntent.getActivity(context, leadidforstatus,
myIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.noti)
.setContentTitle("LMS notification")
.setContentIntent(pendingIntent)
.setContentText(intent.getStringExtra("messagenotify"))
.setAutoCancel(true);
i = (int) System.currentTimeMillis();
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(i, mBuilder.build());
In that I set one list of notifications. In that some displayed and some not displayed. But I want to cancel all un shown notifications.
I used mNotificationManager.cancleAll() but that is cancel only shown notifications.
thanks in advance.
I think the problem here is that The Notification is launched immediately after creating it and your not using the AlarmManager to schedule this Notification.
Solution Should be to schedule Alarms via an AlarmManager which will trigger the Notification Code above.
This requires 3 parts:
Register a BroadCastReceiver & Build a Notification when its triggered:
public class UtilityReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// .. Here is where you really want to build the notification and notify
// This will be triggered by the AlarmManager from the Code below
PendingIntent pendingIntent = PendingIntent.getActivity(context, leadidforstatus, myIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.noti)
.setContentTitle("LMS notification")
.setContentIntent(pendingIntent)
.setContentText(intent.getStringExtra("messagenotify"))
.setAutoCancel(true);
i = (int) System.currentTimeMillis();
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(i, mBuilder.build());
}
Schedule an Alarm with the AlarmManager to send a BroadCast which the Receiver above is listening for:
// Create an Intent to Launch
Intent notificationIntent = new Intent(context, UtilityReceiver.class);
// Use a Pending Intent to Launch the Alarm
PendingIntent notificationPendingIntent = PendingIntent.getBroadcast(context,
PendingIntent.FLAG_ONE_SHOT, notificationIntent, Intent.FILL_IN_DATA);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, timeForAlarmInMillis, notificationPendingIntent);
Then when you encounter the situation when you no longer want notifications to show for your app, you tell the AlarmManager to remove them from its queue of Alarms by Rebuilding the pending Intent and using AlarmManager to Cancel it.
// Create an Intent to Launch
Intent notificationIntent = new Intent(context, UtilityReceiver.class);
// Use a Pending Intent to Launch the Alarm
PendingIntent notificationPendingIntent = PendingIntent.getBroadcast(context,
PendingIntent.FLAG_ONE_SHOT, notificationIntent, Intent.FILL_IN_DATA);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// *********Important this will cancel all the Matching PendingIntents
alarmManager.cancel(notificationPendingIntent);
Good Luck, and be sure to register your Receiver in your Activity or Manifest.
NotificationManager maintains list of all notification mNotificationList and performs cancel or cancelAll operations on this list
I tried searching in Google source code of NotificationManager.java and NotificationManagerService.java in notify(),enqueueNotificationWithTag() and cancelAllNotification() But there is no implementation to cancel previously unshown notification
As per your comment, if your user is deleted and his notification arrives then user is already deleted so notification has no meaning
i = (int) System.currentTimeMillis();
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(i, mBuilder.build());
// i should be Id for this notification, i think you want to pass
// time in mili second here
I think you are searching similar to this,
How to dismiss notification after action has been clicked
Just check the answer on that post. Use the id to cancel that particular Notification
I think the id part in your code is this,
i = (int) System.currentTimeMillis();
I have set up a notification which will be shown 4 hours after the App being destroyed.
But as I am destroying the App, the notification is coming immediately and also after 4 hours.
Here's my Main Activity's onDestroy():
#Override
public void onDestroy() {
super.onDestroy();
Intent myIntent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
//alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 3600*1000*4, 3600*1000*4, pendingIntent);
}
and here's my AlarmReceiver.class:
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent mainIntent = new Intent(context, Main.class);
NotificationManager notificationManager
= (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
android.app.Notification noti = new NotificationCompat.Builder(context)
.setAutoCancel(true)
.setContentIntent(PendingIntent.getActivity(context, 0, mainIntent,
PendingIntent.FLAG_UPDATE_CURRENT))
.setContentTitle("Title")
.setContentText("It's been so Long!!!")
.setSubText("Please return back to App & Learn more Duas.")
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setVibrate(new long[] {700,700,700,700})
.setSmallIcon(R.drawable.ic_launcher)
.setTicker("Important Notification")
.setWhen(System.currentTimeMillis())
.build();
notificationManager.notify(0, noti);
}
}
I want that Notification should be shown after every 4 hours & not immediately of App being destroyed.
Any help would be highly Appreciated.
Thanks in Advance.
It is because of small mistake
just change this line
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 3600*1000*4, 3600*1000*4, pendingIntent);
TO this
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, (System.currentTimeMillis()+(3600*1000*4)), 3600*1000*4, pendingIntent);
I'm trying to send a notification to a user at a specific time using an Alarm Manager. Basically, nothing happens at all and to me the code looks fine. My code for the Alarm Manager is below:
/** Notify the user when they have a task */
public void notifyAtTime() {
Intent myIntent = new Intent(PlanActivity.this , Notification.class);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(PlanActivity.this, 0, myIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE, 17);
calendar.set(Calendar.SECOND, 00);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000 , pendingIntent);
}
The code for the notification, which is in the "Notification" class is below:
public class Notification extends Service {
#Override
public void onCreate() {
Toast.makeText(this, "Notification", Toast.LENGTH_LONG).show();
Intent intent = new Intent(this,PlanActivity.class);
PendingIntent pending = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Football")
.setContentText("Don't forget that you have Football planned!")
.setContentIntent(pending);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(0, mBuilder.build());
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
The Toast which is set in the Notification class also doesn't come up. I don't know if it's something really silly that I'm missing but any help would be greatly appreciated! :)
This is your receiver class :
public class OnetimeAlarmReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
//Toast.makeText(context, "Repeating Alarm worked.", Toast.LENGTH_LONG).show();
// try here
// prepare intent which is triggered if the
// notification is selected
Intent intent = new Intent(this, NotificationReceiver.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
// build notification
// the addAction re-use the same intent to keep the example short
Notification n = new Notification.Builder(this)
.setContentTitle("New mail from " + "test#gmail.com")
.setContentText("Subject")
.setSmallIcon(R.drawable.icon)
.setContentIntent(pIntent)
.setAutoCancel(true)
.addAction(R.drawable.icon, "Call", pIntent)
.addAction(R.drawable.icon, "More", pIntent)
.addAction(R.drawable.icon, "And more", pIntent).build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, n);
}
}
In Second Activity to set Alerm :
private void setAlarm(){
Intent intent = new Intent(this, OnetimeAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, REQUEST_CODE, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + alarm_time , pendingIntent);
System.out.println("Time Total ----- "+(System.currentTimeMillis()+total_mili));
}
I would like to recommend this tutorial How to send notification
Try to put your notification code in the onStartCommand function instead of onCreate.
Writing the alarmmanager code in the onCreate method of the LAUNCHER activity of the app solved my problem