I started working with Notifications and to improve user expirirence I added button to notification "MARK AS READ", so when it is pressed - message will hide;
I had a few problems, in database each message has "read" field which is boolean, in method onDataChange() I loop and check if any of messages have this field as false if they have I call makeNotification(), looks fine, where is problem??? - e.x. I have 2 notifications, I cancel one(the app goes to database and change field to true, so now onDataChange() will be called), but another isn't cancelled and because onDataChange() was called now I have same notification appeared twice.....
I tried to fix this by building array of messages that are read and already displayed, not the best solution I think, but even previous problem was somehow solved this is a wierd one.
When notitifcation appears in notification list it has button "MARK AS READ", when I press it notififcation hides, but only if I start from the highest to the lower ones, so if I press second notification first foldes, if I press third first folds..
In onCreate() counter is set to 1;
public void makeNotification()
{
Intent activityIntent = new Intent(this, Notifications.class);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, activityIntent, 0);
Intent broadcastIntent = new Intent(getApplicationContext(), NotifUpdater.class);
broadcastIntent.putExtra("seconds", message.getSeconds());
broadcastIntent.putExtra("id", String.valueOf(counter));
PendingIntent actionIntent = PendingIntent.getBroadcast(this, 0,
broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this, App.CHANNEL_ID)
.setVibrate(new long[]{100, 0, 100})
.setSmallIcon(R.drawable.ic_shield)
.setContentTitle(message.getTime() + " | " + message.getClient())
.setContentText(message.getMessage())
.setContentIntent(contentIntent)
.setAutoCancel(true)
.setOnlyAlertOnce(true)
.addAction(0, "MARK AS READ", actionIntent)
.build();
notificationManager.notify(counter, notification);
counter += 1;
}
// Broadcast which is triggered by pressing button
public class NotifUpdater extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
String seconds = intent.getStringExtra("seconds");
int id = Integer.parseInt(intent.getStringExtra("id"));
database.getReference("latest").child(seconds).child("read").setValue(true);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
notificationManager.cancel(id);
}
}
You should have : FLAG_CANCEL_CURRENT
like :
PendingIntent actionIntent = PendingIntent.getBroadcast(this, NOTIFICATION_ID, buttonIntent, PendingIntent.FLAG_CANCEL_CURRENT);
not FLAG_UPDATE_CURRENT
Regarding your first issue, I'd just set an indicator for each notification, "wasShown" or something of the sort that is only set to true once you have showed the notification and when ever you are iterating your notifications, only show those who has "wasShown" set to false.
Regarding your 2nd problem, I'm not familiar with FirebaseDatabase but it sounds like its an ID problem. Did you make sure the ID you are getting from the intent is the right one?
Related
I can't seem to figure out why I can'y get my actions to show up on a remote notification. I have seen several tutorials on making it happen, and followed them, still no actions show up. The end goal is to have a "Reply" action where you can type in a response and send a reply through the notification, much like the standard text message notification.
I couldn't get that to show up, so I decided to add a second action, that is just a basic action, neither are showing up. I'll post up my sendNotification method, hopefully someone can see what I am doing wrong...
private void sendNotification(String body, String id) {
Intent i;
PendingIntent pi;
if(user.role.equals(Strings.roleMember) { //This is just to separate logic
i = new Intent(this, NotificationReceiver.class);
pi = PendingIntent.getBroadcast(this, 0, i, 0);
} else {
i = new Intent(this, AgentChatActivity.class);
pi = PendingIntent.getActivity(this, 0, i, 0);
}
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra(Strings.chatID, id);
RemoteInput input = new RemoteInput.Builder(Strings.textReply).setLabel("Reply").build();
NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(android.R.drawable.ic_dialog_info, "Reply", pi)
.addRemoteInput(input).build();
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, Strings.channelID)
.setSmallIcon(R.drawable.ic_stat_notify)
.setContentTitle("New Message")
.setContentText(body)
.setAutoCancel(true)
.setCategory(NotificationCompat.CATEGORY_MESSAGE) //I have tried without this too
.setPriority(NotificationCompat.PRIORITY_MAX)
.addAction(replyAction)
.addAction(android.R.drawable.ic_dialog_alert, "reply", pi); //this is the second I added just to test
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(Strings.channelID, "General Messages", NotificationManager.IMPORTANCE_HIGH);
manager.createNotificationChannel(channel);
}
manager.notify(0, builder.build());
}
According to everything I have seen online, that should have actions attached to the notification, however I run it in the emulator (Pixel 6 API 27) and the notification shows up, but no actions are on it. I have tried without the second action, I have tried with only the second action, nothing shows up, just the basic notification. My build settings are set to minSdk 21, compileSdk and targetSdk 33. I would be more than happy to post any more code or anything else anyone needs, I can't figure it out. Thank you.
I'm creating an android java app that contains a part creates notifications to be confirmed or denied by the user, and the notifications cannot be dismissed by the user, only via the app
The problem is that once I create the notification, the action buttons work perfectly, but if I create another notification, the old notifications' buttons don't work anymore
Which causes that if the user tried to confirm or deny any old notification (via their button 'Confrm' & 'Deny'), the actions that the button must perform don't happen, but only happen with the last(newest) notification
So my question is how to keep the old notifications' buttons active after creating a new notification
I use the code below (with changing the NotificationID)
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification.Builder mbuilder = new Notification.Builder(MainActivity.this);
mbuilder.setContentTitle("Confirmation");
mbuilder.setContentText("Do you want to confirm that you want to wake up at 7 am?");
mbuilder.setSmallIcon(R.drawable.app_icon);
mbuilder.setDefaults( Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
mbuilder.setOngoing(true);
mbuilder.setAutoCancel(false);
Intent NotificationIntent = new Intent(getApplicationContext(), MainActivity.class);
NotificationIntent.setClass(getApplicationContext(), MainActivity.class);
NotificationIntent.putExtra("NotificationID", String.valueOf((long)(NotificationID)));
NotificationIntent.setType("CONFIRMATION=true");
PendingIntent PendingIntent1 = PendingIntent.getActivity(getApplicationContext(), 1, NotificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
mbuilder.addAction(R.drawable.app_icon, "CONFIRM", PendingIntent1);
NotificationIntent.setType("CONFIRMATION=false");
PendingIntent PendingIntent2 = PendingIntent.getActivity(getApplicationContext(), 1, NotificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
mbuilder.addAction(R.drawable.app_icon, "DENY", PendingIntent2);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("1", "Confirmations", NotificationManager.IMPORTANCE_DEFAULT);
channel.enableLights(true);
channel.setLightColor(Color.BLUE);
channel.setShowBadge(true);
channel.enableVibration(true);
mbuilder.setChannelId("1");
if (mNotificationManager != null) {
mNotificationManager.createNotificationChannel(channel);
}
} else {
mbuilder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);
}
if (mNotificationManager != null) {
mNotificationManager.notify((int)(NotificationID), mbuilder.build());
}
I change the intent type to know the clicked button because the intent can contain only one type, but if I add a flag instead, it will duplicate which will cause a problem in recognizing which button is clicked after launching the MainActivity, so it's easier to me to do that.
Thanks
I have an android App that makes notifications. I can generate a notification together with a button, without a problem. My problem is the button's action. I want the button to call a method, for example a text-printing method. I'm using addAction(icon, "title", pendingIntent).
public void sendNotification(Context context) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(context.getApplicationContext(), SomeClass.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context.getApplicationContext(), (int) System.currentTimeMillis(), intent, 0);
NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.icon)
// This creates the button and it is using a pending intent.
.addAction(R.drawable.icon, "Print something", printPendingIntent)
// Clicking on notification takes you back to the App.
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setContentTitle("My Title")
.setContentText("Some text");
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
So the problem is in printPendingIntent, (no code written as you can see),
how do I access / call a method by using this pending intent?
Thanks for answers and sorry if the question is not clear and detailed enough.
add intent.putExtra("key","printmethod"); then receive the data in your SomeClass using getIntent().getExtras("Key"); if the value is matched then you can call your desired method in that activity.
I have a fairly simple app that takes the input from a user and then sets it as a notification. The user can create as many notifications as he/she likes. I want the user to click the notification and get taken to a new activity called ResultActivity. ResultActivity in turn reads in the putExtras from the notifications intent and shows it to the user. The code below allows me to do almost everything I wanted, except anytime a notification is pressed, I receive the putExtra of the last created notification.
Intent notificationIntent = new Intent(ctx, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(ctx, i,notificationIntent,PendingIntent.FLAG_CANCEL_CURRENT);
NotificationManager nm = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
Resources res = ctx.getResources();
NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx);
builder.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(res,R.drawable.ic_launcher))
.setTicker("Remember to " + text.getText())
.setWhen(System.currentTimeMillis()).setAutoCancel(true)
.setContentTitle(text.getText());
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, ResultActivity.class);
String pass = text.getText().toString();
resultIntent.putExtra("title", pass);
resultIntent.putExtra("uid", i);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
new Uri.Builder().scheme("data").appendQueryParameter("text", "my text").build();
builder.setContentIntent(resultPendingIntent);
Notification n = builder.build();
n.flags = Notification.FLAG_NO_CLEAR;
nm.notify(i++, n);
text.setText(null);
Open the application
Type in "One"
Hit ok
Notification is sent
Open the application
Type in "Two"
Hit ok
Notification is sent
Now you have two notifications. One that says "One" and one that says "Two". If you click on the notification "Two" it takes you to a screen that says "Two". Perfect!
If you click on the notification "One" it takes you to a screen that says "Two". BROKEN!
ResultActivity.java
public class ResultActivity extends Activity {
String title = null;
TextView text;
int i=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
text = (TextView) findViewById(R.id.textView1);
title = getIntent().getStringExtra("title");
i = getIntent().getIntExtra("uid", 0);
text.setText(title);
}
I know this was a lot time ago but i feel that the answers have not said anything about the problem in your code.
So the problem is pretty much here
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
So you create a pendingIntent from the stackbuilder whith the flag of update_current. If you look at FLAG_UPDATE_CURRENT it says
/**
* Flag indicating that if the described PendingIntent already exists,
* then keep it but replace its extra data with what is in this new
* Intent. For use with {#link #getActivity}, {#link #getBroadcast}, and
* {#link #getService}. <p>This can be used if you are creating intents where only the
* extras change, and don't care that any entities that received your
* previous PendingIntent will be able to launch it with your new
* extras even if they are not explicitly given to it.
*/
public static final int FLAG_UPDATE_CURRENT = 1<<27;
So what happens in your use case is that you create two identical pendingintents from the stackbuilder and the second intent overrides the first one . Actually you never create a second you just update the extras of the first one.
So unfortunately there is no available flag for your use case , but there is a good hack around it. What you can do is use the setAction of your resultIntent and place a random string or a string that makes sense to your app.
eg. resultIntent.setAction("dummy_action_" + notification.id);
This will make your resultIntent unique enough , so that the pendingIntent will create it rather than updating a previous one.
Set different requestCode helps me create and update current intent.
val pendingIntent = PendingIntent.getActivity(
this,
notificationID,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
)
You create multiple intents that are mixed. I cleaned up the code (but did not test it)
NotificationManager nm = (NotificationManager) ctx
.getSystemService(Context.NOTIFICATION_SERVICE);
Resources res = ctx.getResources();
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, ResultActivity.class);
String pass = text.getText().toString();
resultIntent.setData(new Uri.Builder().scheme("data")
.appendQueryParameter("text", "my text").build());
resultIntent.putExtra("title", pass);
resultIntent.putExtra("uid", i);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx);
builder.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(
BitmapFactory.decodeResource(res,
R.drawable.ic_launcher))
.setTicker("Remember to " + text.getText())
.setWhen(System.currentTimeMillis()).setAutoCancel(true)
.setContentTitle(text.getText())
.setContentIntent(resultPendingIntent);
Notification n = builder.build();
n.flags = Notification.FLAG_NO_CLEAR;
nm.notify(i++, n);
text.setText(null);
Use some random requestCode to seperate two notifications
PendingIntent pendingIntent = PendingIntent.getActivity(context, CommonTools.getRandomNumber(1, 100),
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
public int getRandomNumber(int min, int max) {
// min (inclusive) and max (exclusive)
Random r = new Random();
return r.nextInt(max - min) + min;
}
Just set your pending request code to System.currentTimeMillis().toInt(). It worked.
val pendingNotificationIntent: PendingIntent = PendingIntent.getBroadcast(
this,
System.currentTimeMillis().toInt(),
notificationIntent,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
I want to launch a notification. When I click on it, it opens a NEW window of the app.
Here's my code:
public class Noficitation extends Activity {
NotificationManager nm;
static final int uniqueID = 1394885;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent= new Intent (Intent.ACTION_MAIN);
intent.setClass(getApplicationContext(), SchoolBlichActivity.class);
PendingIntent pi=PendingIntent.getActivity(this, 0, intent, 0);
String body = " body";
String title = "title!";
Notification n =new Notification(R.drawable.table, body, System.currentTimeMillis());
n.setLatestEventInfo(this, title, body, pi);
n.defaults = Notification.DEFAULT_ALL;
n.flags = Notification.FLAG_AUTO_CANCEL;
nm.notify(uniqueID,n);
finish();
}
by the way, if i add nm.cancel(uniqueID) before the finish(), it creates the notification and immediately deletes it...
Thanks for the help :D
You might want to just add a notification in the notification bar, and when the user clicks it, it will launch the actual Activity. This way the user won't be interrupted in whatever he's doing.
Create the status bar notification like this:
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.notification_icon, "Hello", System.currentTimeMillis());
Intent notificationIntent = new Intent(this, myclass.class);
notification.setLatestEventInfo(getApplicationContext(), "My notification", "Hello world!", notificationIntent, PendingIntent.getActivity(this, 0, notificationIntent, 0));
mNotificationManager.notify(1, notification);
http://developer.android.com/guide/topics/ui/notifiers/notifications.html
Are you just trying to open a notification window in a current activity? Because if you are I dont think you need to launch it with an intent. You normally only use intents to launch new services or activities in your app unless youve built a custom view and activity/service which is to take place within the notification box. I see you have it set up in its own class which is fine but I think the way your doing it by default would open an entire new view.
If you need to launch a notification during a process or something like a button click you dont need to have the intent there.....or at least I never did :) What exactly are you trying to achieve with the notification.