I'm new to android programming and I just learned how to make a notification via an Intent and a PendingIntent. I wondered if I could make this notification clickable (link to my MainActivity) without starting a new Activity.
This is what I have right now (AlarmReceiver excluded) as a function in my MainActivity:
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
manager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
I reckoned I should change "this" to something else, but I wouldn't know how to do this. Any help would be appreciated!
You can use the notification Builder, in my case the compat builder.
NotificationCompat.Builder
Setting the content, I've got mine from the params. You have to replace them with your respected once.
builder.setContentTitle(params.getTitle())
.setContentText(params.getText())
.setWhen(params.getTime())
.setTicker(params.getTickerText())
.setPriority(params.getPriority())
.setOngoing(params.isOngoing())
.setOnlyAlertOnce(true)
.setAutoCancel(params.getAutoCancel())
.setStyle(params.getStyle());
Creating PendingIntent and also adding it to the Notification through the builder. This intent should be pointing to your Launcher Activity and from there you can handle it in OnCreate.
builder.setContentIntent(pendingIntent);
Then push the notification
mNotificationManager.notify(id, notification);
You can also make these notifications pointing to a BroadCastReceiver and handle a click on the notification from there, on its onReceive method.
Intent alarmIntent = new Intent(this, MainActivity.class);
PendingIntent intent = PendingIntent.getActivity(this, 0,
alarmIntent , PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
manager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); ...try this
Related
As a beginner, I wrote a code for notification. I put that code in MainActivity.
Now the problem is, my app shows notification at sharp 8 AM. But During other time, if i restart my app, it shows notification again(at any other time). Basically I am not cancelling it notification as it appears. Though I have put AutoCancel true. Am i missing something?
Code in MainActivity, onCreateMethod:
calendar = Calendar.getInstance();
PendingIntent pendingIntent ;
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE,00);
calendar.set(Calendar.SECOND, 00);
Intent intent = new Intent(MainActivity.this, NotificationBroadcasrReceiver.class);
intent.putExtra("NotificationType","GoodMorning");
pendingIntent = PendingIntent.getBroadcast(
getBaseContext(), (int)System.currentTimeMillis(), intent,
PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getBaseContext()
.getSystemService(getBaseContext().ALARM_SERVICE);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent);
After this it comes to BroadCast Receiver :
the code inside onReceive is
Intent intentNew = new Intent(context, CustomIntentService.class);
intentNew.putExtra("NotificationType",intent.getStringExtra("NotificationType"));
context.startService(intentNew);
Now custom intent servcice class has following code..
Intent notificationIntent = new Intent(this,CustomActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
mBuilder.setSmallIcon(R.drawable.happiness_icon);
mBuilder.setAutoCancel(true);
mBuilder.setContentIntent(pendingIntent);
mBuilder.setContentTitle("Positive Minds");
mBuilder.setCustomBigContentView(remoteViews);
mBuilder.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
NotificationManager mNotificationManager = (NotificationManager)this
.getSystemService(this.NOTIFICATION_SERVICE);
mNotificationManager.notify((int)System.currentTimeMillis(), mBuilder.build());
I used below mentioned code to fix this.
if(calendar1.getTime().compareTo(new Date()) < 0)
calendar1.add(Calendar.DAY_OF_MONTH, 1);
I am working on application which is get the alarm time from database every 2 AM and then at the specified time the activity shows up, my app works fine, but when I manually change the data/time of the device, previous alarms are triggered and I should prevent to this to happens.
Here is my PendingIntent:
Intent i = new Intent(mContext, AlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(G.context, _id, i,
PendingIntent.FLAG_UPDATE_CURRENT);
Which each _id is unique and when I make a receiver for date changed event before my alarm cancel method fired previous alarms go off!
Can some body help to solve this problem?
Try this code:
Intent intent = new Intent(this, Mote.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 1253, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); alarmManager.cancel(pendingIntent);
For cancel the alarm:
Intent intent = new Intent(this, Mote.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 1253, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
Edit
Well you can look for the answer and modify as per your requirements:
How to stop Android AlarmManager when there is a manual system time change?
AlarmManager: how to schedule a daily alarm and deal with time changes
Intent intent1 = new Intent(G.context, DailyAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(G.context,
G.dateTimesetAlarm.getDayOfYear(), intent1, 0);
mAlarmManager.cancel(pendingIntent);
pendingIntent.cancel();
I have scheduled android notifications using alarm manager but I couldn't cancel the notification where I tried to cancel it using this notificationManager.cancelAll(); does not work and then I tried to cancel alarm manager itself, unfortunately, does not work.
Does anyone know how to cancel scheduled notification?
This is how I set alarm manager for notification:
Intent myIntent = new Intent(DirctActivityfinal3.this, MyReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(DirctActivityfinal3.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, timeOff9.getTimeInMillis(), pendingIntent);
I tried this code to cancel alarm manager, but not working I still get notified
Intent intent = new Intent(ViewTicketActivity.this, DeleteNotification.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(ViewTicketActivity.this,0, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
Your PendingIntents are not the same.
To cancel an alarm, the pending intent that you created to cancel the alarm with must be the same as the one you created the alarm with.
e,g in your example, You are passing different classes into each.
Intent myIntent = new Intent(DirctActivityfinal3.this, MyReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(DirctActivityfinal3.this, 0, myIntent, 0);
is not the same as
Intent intent = new Intent(ViewTicketActivity.this, DeleteNotification.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(ViewTicketActivity.this,0, intent, 0);
Complete Sample:
Intent myIntent = new Intent(myContext, MyReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(myContext, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
then either
alarmManager.set(AlarmManager.RTC_WAKEUP, timeOff9.getTimeInMillis(), pendingIntent);
or
alarmManager.cancel(pendingIntent);
Declare Intent, PendingIntent and AlarmManager as global variables
to cancel the scheduled
pendingIntent = PendingIntent.getBroadcast(ViewTicketActivity.this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
alarmManager.cancel(pendingIntent);
I am trying to set repeating alarms in an exact fashion by manually setting an alarm to the next day the moment I receive it in a broadcast. However, I might be missing something and somehow its not working.
The Logic:
When I select the time from a time chooser, I set an exact alarm to the time given and start a pending intent which calls MyBroadCastReceiver.java (extends BroadcastReceiver) when its time. I then forward the intent with another pending intent to AlarmFireActivity. (AlarmFireActivity also has snooze which simply sets a pendingIntent to itself to fire after 5 mins.)
The MyBroadCastReceiver component hence only receives the actual alarms (not snoozes). And its functions are :
a) Get the non-repeating pending intent cancel it, then create another pending intent from the intent and then set it with the milliseconds set to the next day at the same time.
b) Start the AlarmFireActivity and show the alarm.
In AddAlarmActivity
Intent intent = new Intent(context, MyBroadcastReceiver.class);
intent.putExtra(DBHelper.COLUMN_ID,alarm.getId());
AlarmManager alarmManager = (AlarmManager) context.getApplicationContext().getSystemService(Context.ALARM_SERVICE);
if (alarmManager != null) {
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, reminder.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, reminder.getHourOfDay());
calendar.set(Calendar.MINUTE, reminder.getMinuteOfHour());
calendar.set(Calendar.SECOND,0);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
pendingIntent);
BLog("Pending intent added at " + new SimpleDateFormat(utilFunctions.timeFormat).format(calendar.getTime()));
}
Snippet MyBroadCastReceiver.java TaskOne
Logic
Get the intent which MyBroadCastReceiver receives. Reuse the same intent in a new PendingIntent set to the next day at the same time.
Code
AlarmManager alarmManager = (AlarmManager) context.getApplicationContext().getSystemService(Context.ALARM_SERVICE);
if (alarmManager != null) {
PendingIntent p1 = PendingIntent.getBroadcast(context, alarmCurrent.getReminderId(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
if(p1!=null){
alarmManager.cancel(p1);
}
PendingIntent pendingIntent1 = PendingIntent.getBroadcast(context, alarmCurrent.getReminderId(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
//for test
calendar.add(Calendar.MINUTE,1);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
pendingIntent1);
}
MyBroadCastReceiver.java TaskTwo
Logic
If the time when the alarm was set was after the time the alarm is due, do not forward the pending intent to the AlarmFireActivity.
Else forward it to the AlarmFireActivity which shows the screen to dismiss/snooze the alarm.
Code
Calendar timeSet = alarmCurrent.getAlarmReminderSetTime();
Calendar alarmTime = Calendar.getInstance();
if(timeSet!=null && alarmTime.getTimeInMillis() > timeSet.getTimeInMillis()){
Intent intent1 = new Intent(context, AlarmFireActivity.class);
intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent1.putExtra(DBHelper.COLUMN_ID,id);
String ext = extras.getString(DBHelper.TASK_TITLE);
if(ext!=null){
intent1.putExtra(DBHelper.TASK_TITLE,ext);
}
context.startActivity(intent1);
}else{
}
The BroadCastReceiver is doing the second task just fine. However, not the task one. Its not repeating/ resetting a new pending intent. I am guessing I must have messed up the intent/pendingIntent somewhere. I dont know which. Please help/
The solution is restart the phone. I have seen somewhere that there is a bug in a one of the os' 4.3 or so. A pending intent with a request id of 0 might fail at times. And once I restarted the phone it worked. However, there is a more standard solution which is :
Replacing
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, reminder.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
with
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, A_NUMBER_GREATER_THAN_ZERO + reminder.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
so that you are avoiding a pending intent with 0 at all times. Thanks all!
I'm writing something like a reminder for users. Users will set reminders for their events, when the time comes, a repeating alarm will be set to trigger a status bar notification. But the alarm seems non-stop after I selected the notification or cleared the notification. I am not sure where to cancel this repeating alarm. Below are some of the codes:
Set up the repeating alarm in my main activity
alarmTime = Calendar.getInstance();
Intent intent = new Intent(this, AlarmReceive.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmTime.add(Calendar.MINUTE,offset_time);
//Schedule the alarm
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime.getTimeInMillis(), 30 * 1000, sender);
In my OnReceive method, I just display the notification in status bar and set the flag as FLAG_AUTO_CANCEL
manager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
// Set the icon, scrolling text and timestamp
Notification notification = new Notification(R.drawable.medical, text, System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, i, 0);
notification.flags = Notification.FLAG_AUTO_CANCEL;
manager.notify(R.string.service_text, notification);
How can I stop the alarm when the user selects the notification or clears it?
Call cancel() on AlarmManager with an equivalent PendingIntent to the one you used with setRepeating():
Intent intent = new Intent(this, AlarmReceive.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(sender);
I tried various methods and couldnt get it to work, so I decided to do a dirty trick. When I want to cancel my repeating alarm, I use the same method that created my alarm (and hence replacing the old one) and then cancel it right away. With this method if the boolean variable is set to true it creates an alarm ow it replaces and then cancels the replacement which has the same id:
static void CancelRepeatingAlarm(Context context, boolean creating){
//if it already exists, then replace it with this one
Intent alertIntent = new Intent(context, AlertReceiver.class);
PendingIntent timerAlarmIntent = PendingIntent
.getBroadcast(context, 100, alertIntent,PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (creating){
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), INTERVAL, timerAlarmIntent);
}else{
alarmManager.cancel(timerAlarmIntent);
}
In your MainActivity, set the alarm time. If you're going to use multiple alarms, use SharedPreferences to store their respective IDs. Here is the code:
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, _id,intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(),
pendingIntent);
public static Context getContext() {
return mContext;
}
mContext=mainactivity.this;
In your second Activity use same ID from SharedPreferences. In my code, I get the ID from the ArrayList, Alarm_id. Last, you can use the MainActivity context here with MainActivity.getContext(). Here is the code:
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intentAlarm = new Intent(AlarmListviewActivity.this,
MainActivity.class);
PendingIntent morningIntent = PendingIntent.getBroadcast(MainActivity.getContext(), Alarm_id.get(positon),
intentAlarm, PendingIntent.FLAG_CANCEL_CURRENT);
alarmManager.cancel(morningIntent);
morningIntent.cancel();