I am using AlarmManager and NotificationManager with BroadcastReceiver.
When I set an alarm with a specific date, it is working the first time. However, when I modify the date and click the confirm button, the alarm is working any date
immediately. I want to set the alarm interval day after expired date with fixed time.
What is the problem with it? I don't understand at the moment.
confirmButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
//set alarm with expiration date
am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
setOneTimeAlarm();
Toast.makeText(fridgeDetails.this, "Alarm automatic set",
Toast.LENGTH_SHORT).show();
setResult(RESULT_OK);
finish();
}
public void setOneTimeAlarm() {
c.set(Calendar.HOUR_OF_DAY, 14);
c.set(Calendar.MINUTE, 49);
c.set(expiredYear, expiredMonth, expiredDay);
Intent myIntent = new Intent(fridgeDetails.this, AlarmService.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
fridgeDetails.this, 0, myIntent, PendingIntent.FLAG_ONE_SHOT);
am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent);
}
});
AlarmService.java
public class AlarmService extends BroadcastReceiver{
NotificationManager nm;
#Override
public void onReceive(Context context, Intent intent) {
nm = (NotificationManager) context.getSystemService(
Context.NOTIFICATION_SERVICE);
CharSequence from = "Check your fridge";
CharSequence message = "It's time to eat!";
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(), 0);
Notification notif = new Notification(R.drawable.ic_launcher,
"Keep Fridge", System.currentTimeMillis());
notif.setLatestEventInfo(context, from, message, contentIntent);
notif.defaults |= Notification.DEFAULT_SOUND;
notif.flags |= Notification.FLAG_AUTO_CANCEL;
nm.notify(1, notif);
}
}
You need to set the property instead of FLAG_ONE_SHOT. This is for single alarm event not for the repeat. try this
PendingIntent pendingIntent = PendingIntent.getBroadcast(
fridgeDetails.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
see more detail about from here
Edit:
As you do for notification with PendingIntent
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,new Intent(), 0);
In this you pass the empty object of Intent you need to pass the class name for that when you click on notification which Activity will be launch like in Alarm set time you do
Intent myIntent = new Intent(fridgeDetails.this, AlarmService.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
fridgeDetails.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
now just pass the Acitivity name in the intent like suppose you want to launch your home activity and activity name like "homeactivity"
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,new Intent(context,HomeActivity.class), 0);
Related
I added a notification feature to my app, when the user clicks on the notification it sends him to a certain activity in my app, but I also want it to change an integer variable number, I tried defining the variable static and do:
ActivityName.Variable = ActivityName.Variable + 1 or ActivityName.Variable++;
And it actually worked! but only when I change the date on my phone manually, so when the user sees the notification after waiting 1 day (the notification is daily) and clicks on it...he get to the activity but with no increase in the variable.
here's the notification codes:
public void setNotificationOn() { //This method sets the notification...so after 24h it will be triggered
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 24);
Intent intent = new Intent(getApplicationContext(), NotificationReceiverActivity.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),
100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
package com.example.wordspuzzlejsontest;
public class NotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
LevelActivity.stars++; //This is the variable which I'm trying to increase
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent repeating_intent = new Intent(context, LevelsListActivity.class);
repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity
(context, 100, repeating_intent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentIntent(pendingIntent)
.setSmallIcon(android.R.drawable.star_big_off)
.setContentTitle("Collect your daily star")
.setContentText("Click to collect your daily star")
.setAutoCancel(true)
.setColor(Color.BLUE);
notificationManager.notify(100, builder.build());
}
}
I am scheduling events and creating the notification for the same on weekly basis or daily basis.The notification is being displayed at correct time.
Problem
I want to delete the notification once the scheduled event is deleted. But I get the notification even if event is deleted. I tried deleting the Pending Intent by passing the same unique_id(eventId) that I have used for creating that intent, but its not deleting. Please find my code below:
creating notification
Intent intent = new Intent(this, MyReceiver.class);
HABIT_NAME = habitName.getText().toString();
intent.putExtra("HABIT_NAME", habitName.getText().toString());
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), eventId, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
if(daysNo.size() == 7){ //alarm for every day
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,reminderLifeTS.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}else{ // specific days of week
for(int i=0;i<daysNo.size();i++){
int day = getWeek(daysNo.get(i));
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, day);
c.set(Calendar.HOUR_OF_DAY, reminderLifeTS.get(Calendar.HOUR_OF_DAY));
c.set(Calendar.MINUTE, reminderLifeTS.get(Calendar.MINUTE));
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
c.getTimeInMillis(),7*24*60*60*1000, pendingIntent);
}
}
Service class
mManager = (NotificationManager) this.getApplicationContext().
getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity(
this.getApplicationContext(),0, intent1,PendingIntent.FLAG_ONE_SHOT);
// megha
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.app_icon)
.setContentTitle("DharmaLife")
.setContentText(AddScheduleEventActivity.HABIT_NAME)
.setContentIntent(pendingNotificationIntent);
Notification note = mBuilder.build();
note.defaults |= Notification.DEFAULT_VIBRATE;
note.defaults |= Notification.DEFAULT_LIGHTS;
note.flags|= Notification.FLAG_AUTO_CANCEL;
PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK |
PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG");
wakeLock.acquire();
Deleting Notification
Intent intent = new Intent();
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), eventId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
pendingIntent.cancel();
AlarmManager am = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
am.cancel(pendingIntent);
EDIT
to keep the list of all the pending intents created, I am saving it in arrayList along with its unique id:
notificationData.setAlarmManager(alarmManager);
notificationData.setPendingIntent(pendingIntent);
notificationData.setEventId(eventId);
LifeLiteral.NOTIFICATION_STACK.add(notificationData);
to delete the notification:
for(NotificationData i : LifeLiteral.NOTIFICATION_STACK){
if(i.getEventId() == eventId){
pendingIntent = i.getPendingIntent();
alarmManager = i.getAlarmManager();
alarmManager.cancel(pendingIntent);
pendingIntent.cancel();
}
}
but still notifications are not getting deleted. Please guide.
When attempting to delete the PendingIntent you aren't passing an Intent that matches the original Intent (because the Intent you pass to getBroadcast() is empty). Change your delete code to this:
Intent intent = new Intent(this, MyReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(),
eventId, intent, 0);
AlarmManager am = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
am.cancel(pendingIntent);
// Cancel the `PendingIntent` after you've canceled the alarm
pendingIntent.cancel();
I'm new to this, so I'm a bit lost.
I have built a notification and passed it to the alarm manager as a pendingIntent, however instead of waiting the interval to trigger the alarm and showing the notification, the notification is instantly shown.
What have I done wrong, that isn't allowing the alarm to be set properly?
public class NotificationController{
Context context;
public void createNotification(Context context){
this.context = context;
Notification notification = getNotification();
//creates notification
Intent intent = new Intent(context, NotificationReceiver.class);
intent.putExtra(NotificationReceiver.NOTIFICATION_ID, 1);
intent.putExtra(NotificationReceiver.NOTIFICATION, notification);
PendingIntent pIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
//schedules notification to be fired.
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 10000 , pIntent);
}
private Notification getNotification(){
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, 0);
Notification.Builder builder = new Notification.Builder(context)
.setContentTitle("Reminder")
.setContentText("Car service due in 2 weeks")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent);
return builder.build();
}
}
my receiver
public class NotificationReceiver extends BroadcastReceiver {
public static String NOTIFICATION_ID = "notification-id";
public static String NOTIFICATION = "notification";
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = intent.getParcelableExtra(NOTIFICATION);
int id = intent.getIntExtra(NOTIFICATION_ID, 0);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(id, notification);
}
}
I have also registered with <receiver android:name=".NotificationReceiver" > in the AndroidManifest.
In this line
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 10000 , pIntent);
You specify that the alarm has to fire at 10 seconds after the device has been booted (which is in the past, so the alarm fires immediately). If you would want it 10 seconds after you set the alarm, you use the number of milliseconds since the device has been booted PLUS 10 seconds:
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, System.currentTimeMillis() + 10000 , pIntent);
Try this:
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, System.currentTimeMillis()+10000 , pIntent);
For me old methods are killing after few hours . Please see my code that i am using for different OS versions. May be helpful.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
AlarmManager.AlarmClockInfo alarmClockInfo = new AlarmManager.AlarmClockInfo(alarmTime, pendingIntent);
alarmManager.setAlarmClock(alarmClockInfo, pendingIntent);
}
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);
}
else {
alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);
}
Thanks
Arshad
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
and
Intent notifyIntent = new Intent(this, MyReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, NotificationKeys.NOTIFICATION_ID, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Calendar alarmStartTime = Calendar.getInstance();
alarmStartTime.set(Calendar.SECOND, 5);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, alarmStartTime.getTimeInMillis(), pendingIntent);
If you want to set is at a excat time, you should use setExact. Unfortunalety there is no setExactRepating so you have to create this yourself. Schedule a new alarm after one executes or something like that
for more refer https://stackoverflow.com/a/30812993/8370216
I am working on an android application but the problem is that I have to alert user through a message on notification bar which will occur after ten(10) days ,like in candy crush game it gives alert of full lives after some hours. I am a beginner in android so I am confused about the implementation of this scenario. Please guide me of its implementation with code.
You can do so with the AlarmManager and the BroadcastReceiver
AlarmManager
Intent myIntent = new Intent(this, TimeAlarm.class);
pendingIntent = PendingIntent.getService(AndroidAlarmService.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.DAY_OF_MONTH, 10);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
BroadcastReceiver
public class TimeAlarm extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent paramIntent) {
// Request the notification manager
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// Create a new intent which will be fired if you click on the notification
Intent intent = new Intent("android.intent.action.VIEW");
// Attach the intent to a pending intent
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Create the notification
Notification notification = new Notification(R.drawable.icon, "Something new!"), System.currentTimeMillis());
notification.setLatestEventInfo(context, "Something new!", "Description",pendingIntent);
// Fire the notification
notificationManager.notify(1, notification);
}
}
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