Multiple Notifications not showing in android - android

In my android app I'm willing to show multiple notifications on a particular day,for this I'm using Alarm Manager and Broadcast Receiver problem is when I used alarm it worked fine but when I add notification builder to show the notification its not working
Here is my mainActivity
public static final String ACTION_ONE = "Hello, Test Message 1";
public static final String ACTION_TWO = "Hello, Test Message 2";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AlarmManager alarmManager1 = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
Intent myIntent1 = new Intent(this, AlarmBroadCustReciver.class);
myIntent1.setAction(ACTION_ONE);
PendingIntent pendingIntent1 = PendingIntent.getBroadcast(this, 1253, myIntent1,
PendingIntent.FLAG_UPDATE_CURRENT);
// Set the time for first alarm here
cal.set(2015, 10, 20, 15, 55);
alarmManager1.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent1);
Intent myIntent2 = new Intent(this, AlarmBroadCustReciver.class);
myIntent2.setAction(ACTION_TWO);
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(this, 1263, myIntent2,
PendingIntent.FLAG_UPDATE_CURRENT);
// Set the time for second alarm here
cal.set(2015, 10, 20, 15, 56);
alarmManager1.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent2);
// In this way set time for all the rest of the alarms
Here is BroadCastReceiver
public class AlarmBroadCustReciver extends BroadcastReceiver {
public static final String ACTION_ONE = "Hello, welcome to the Server1";
public static final String ACTION_TWO = "Hello, welcome to the Server2";
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher));
builder.setContentTitle(context.getString(R.string.app_name));
if (intent.getAction().equalsIgnoreCase(ACTION_ONE)) {
builder.setContentText("Alarm one");
} else {
builder.setContentText("Alarm two");
}
Notification notification = builder.build();
int notificationID = 0;
notificationManager.notify(notificationID, notification);

You need to pass different notification id for each Notification . If you pass same id (i.e., 0 in your case), the existed notification will be updated with the new data.
change the notification id: eg have a variable and increment it. notificationid++

I had a similar issue, I was creating multiple notifications with different IDs, however, when I clicked on one, only the first one opened the specific scree, all the sequential notifications were ignore (clicking on them didn't do anything, they were just dismissed). Then I tried to do this:
intent.setAction(context.getPackageName() + "." + notificationId);
Which means that each unique notification also carries its own unique Intent and in this case the Intents weren't ignored and each of them opened the needed screen. I must note that my Intents were the same (e.g. NoteDetails.class), so I guess I had to separate them somehow...i'm glad it worked anyways.

Box's answer was a nudge in the right direction for me.
I just had to change the requestCode in the PendingIntent I was passing to the AlarmManager, so it wasn't the same value.
Old code:
PendingIntent pI = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
New code:
PendingIntent pI = PendingIntent.getBroadcast(context, notificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT);

Related

Android AlarmManager only sending last scheduled notification

I am creating a research app that should prompt the user 4 times a day to enter their mood - by sending a notification, which when clicked launches the correct Activity. I am able to schedule these notifications using AlarmManager, however only the last scheduled notification ever shows. So although I schedule them for 9AM, 2PM, 5PM, and 8PM, it only ever sends a notification at 8PM.
How can I get all of the scheduled notifications to show?
Here is my code for setting (one of) the alarms (from a notification manager class). Note that al alarms are set using the same instance of AlarmManager:
cal.setTimeInMillis(System.currentTimeMillis());
cal.set(Calendar.HOUR_OF_DAY, 9);
cal.set(Calendar.MINUTE, 0);
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), createPendingIntent(9, this));
Here is the createPendingIntent method (in the same notification manager class):
public static PendingIntent createPendingIntent(int hour, Context c){
Intent notificationIntent = new Intent(c, AlarmBroadcastReceiver.class);
notificationIntent.putExtra("time", hour);
PendingIntent pendingIntent = PendingIntent.getBroadcast(c, 0 , notificationIntent , PendingIntent.FLAG_UPDATE_CURRENT);
return pendingIntent;
}
Here is the BroadcastReceiver for the alarm:
public class AlarmBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationSender.createNotification(context);
}
}
And finally the createNotification method:
public static void createNotification(Context c){
Log.e("notif?", "creating");
Intent intent = new Intent(c, UpdateMoodActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
int notificationId = new Random().nextInt();
PendingIntent pendingIntent = PendingIntent.getActivity(c, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(c, "com.lizfltn.phdapp.notifChannelID")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("SoftMood")
.setContentText("Please record your mood")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(c);
notificationManager.notify(notificationId, builder.build());
}
Yes I know this isn't the best-practice way of doing things, or even the neatest, but unfortunately I need to get code working ahead of writing good code :P
I've tried various configurations of setting the alarm, e.g. using elapsed realtime instead of RTC, only setting the alarm, setting the exact alarm, etc, but there might be something fundamental I'm not understanding about how those work.
Any help appreciated!
Can you try with same id in pending intent and notify.?
Notification id in createNotification() method is random id.
int notificationId = new Random().nextInt();
and id used in createPendingIntent method is 0.
PendingIntent pendingIntent = PendingIntent.getBroadcast(c, 0 , notificationIntent , PendingIntent.FLAG_UPDATE_CURRENT);
Can you try with using same value for second parameter of getBroadcast?

Changing a variable from Notification Method

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());
}
}

Notification is sent whenever the app is open in Android

I have an app that sends a notification with AlarmManager every day at an exact time.
But it has a bug. The notification is sent whenever the app is open.
How can I get to the notification is send once a day? Thank you
MAINACTIVITY
public class MainActivity extends Activity {
private PendingIntent pendingIntent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Calendar calendar = Calendar.getInstance();
int d = Integer.valueOf(1440);
calendar.setTimeInMillis(System.currentTimeMillis());
Intent i = new Intent(MainActivity.this, Receiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, i, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * d, pendingIntent);
}
}
RECEIVER
public class Receiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
Intent i = new Intent(context, MainActivity.class);
Notification notification = new Notification(R.drawable.ic_launcher,"This is a test message!", System.currentTimeMillis());
long[] vibrate = {100, 100, 200, 300};
notification.vibrate = vibrate;
notification.defaults = Notification.DEFAULT_ALL;
i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity(context, 0, i,PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(context, "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);
notificationManager.notify(0, notification);
}
}
Code to call CallThisClass.class every int d mins
Intent myIntent = new Intent(getActivity(), CallThisClass.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
int d = Integer.valueOf(duration);
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 2);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * d, pendingIntent);
Code to stop calling CallThisClass.class
Intent myIntent = new Intent(getActivity(), CallThisClass.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, myIntent, 0);
alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
CallThisClass.class
public class CallThisClass extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
Log.i("Received", "Broadcast Received !");
// Do your stuff
}
}
Dont forget Receiver inyour AndroidManifest.xml
<receiver android:name=".CallThisClass" />
And Permission
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
You can start calling CallThisClass.class whenever you want. Eg. on a click of a button, or when your main activity start. Just make sure to Stop Calling the class when you dont want it working. Eg You want when the user first installs your application you want every 24 hours there should be something updated (notification or something), rit? in your prefrences store a variable that changes itself only if it is loaded for the first time. Check for that variable every time user enters application. if it is first time Start the Calling code. (now we dont want to call the stop code yet because we cant to keep on calling that class even if the application is closed!) close the application and it will work. And you can have a button in you setting or something for testing that when clicked will run code for not calling the class. It will stop the calling calling class every d mins i.e 24 hours in your case (also you can change the prefrnce to default value on clik of this button so that next time you start activity or click activate or something again that code to start calling that class starts). I hope it helps.
Also, i would suggest a read here for Best practices

strange notifications behaviour

I have a simple application (custom calendar). Every time a user creates event a new AlarmManager with custom broadcast receiver is created to call a notification 5 minuts before the event start. When that time come and user click on the notification a simple activity just shows the events info.
What is the problem: When i run app and create the event for the first time, everything works fine. When user click notification the correct one is displayed. But, when I create the second event, the problem occurs. When the notification for second notification is displayed, it looks fine (the correct information is shown in notification bar), but when i click it the first created event is shown. The same with third, fourth ...
how alarm manager is created, this is located in the activity that create event...
if (hasAlarm) {
Bundle bundle = new Bundle();
bundle.putString("name", eventName);
bundle.putLong("time", dateStart);
bundle.putString("desc", eventDescription);
bundle.putString("location", eventLocation);
bundle.putLong("end", dateEnd);
bundle.putString("username", username);
bundle.putString("password", password);
bundle.putString("mailServer", mailServer);
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
alarmIntent.putExtras(bundle);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,
0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, dateStart
- (1000 * 60 * 5), pendingIntent);
}
and custom broadcast receiver ...
public class AlarmReceiver extends BroadcastReceiver {
private static int id = 0;
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
String desc = bundle.getString("desc");
long time = bundle.getLong("time");
String name = bundle.getString("name");
for (String key : bundle.keySet()) {
Log.d("Bundle ALARM REVEIVER", key + " = \"" + bundle.get(key)
+ "\"");
}
long[] vibrate = { 0, 100, 200, 300 };
Uri alarmSound = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context).setSmallIcon(R.drawable.stat_notify_chat)
.setContentTitle("Upcoming event: " + name)
.setContentText(desc).setWhen(time).setVibrate(vibrate)
.setSound(alarmSound);
Intent viewEvent = new Intent(context, ViewEvent.class);
viewEvent.putExtras(intent.getExtras());
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
viewEvent, 0);
builder.setContentIntent(contentIntent);
NotificationManager mNotificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(id++, builder.build());
}
}
I found where the problem was ...as we can see in the documentation, we need to add PendingIntent.FLAG_UPDATE_CURRENT for broadcast receiver as well, so the full implementation looks like
Intent viewEvent = new Intent(context, ViewEvent.class);
viewEvent.putExtras(intent.getExtras());
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
viewEvent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);

how to schedule a notification using alarm manager

I have defined a receiver which should fire the notification when it is called. This works only if I call the receiver straight away.
I am unable to schedule it for a specific date.
Calendar c = Calendar.getInstance();
c.set(2014, 4, 18, 2, 20, 0);
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(getBaseContext().ALARM_SERVICE);
int id = (int) System.currentTimeMillis();
Intent intent = new Intent(this, TimeAlarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
This is my Receiver class:
public class TimeAlarm extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent paramIntent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent("android.intent.action.VIEW");
intent.setData(Uri.parse("http://www.sdfasdf.ch"));
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Create the notification
Notification notification = new Notification(R.drawable.android_anydont_logo, "sdfs", System.currentTimeMillis());
notification.setLatestEventInfo(context, "something something", "darkside",pendingIntent);
// Fire the notification
notificationManager.notify(1, notification);
}
}
This is the definition in the manifest:
receiver
android:name="com.hack.doneit.utils.TimeAlarm"
android:process=":remote" />
My problem is that i am unable to set the alarm to trigger the receiver at a specific time in the future. A specific day would be enough.
Problem is with the Month value you have set. I believe you thought for month April the value is 4. The value of month starts from 0 , so April will be 3.
Change you code on month as Calendar.APRIL or set value as 3
c.set(2014, Calendar.APRIL, 17, 20, 43, 0);
This should work. Apart from this your codes are perfect.
Note: Your using the Notification deprecated API's . Use Notification Builder

Categories

Resources