Android - Changing notification's ContentText on a button click - java

I have a notification that contains a button, inside that notification .setContentText() there is a proverb shown from an array of strings containing numerous proverbs, what I'm trying to do is when I click that notification button a new proverb is assigned to .setContestText()
I tried looking for other solutions on SO but I got nothing similar
Current result : When I click the button nothing happens
Here is my code so far:
public void notif(){
int icon = getRandomIc();
String Prov = getRandomProverb();
String newProverb = getRandomProverb();
Intent reloadQ = new Intent(this, Splash.class);
PendingIntent piReload = PendingIntent.getService(this, 0, reloadQ, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
Notification notification = mBuilder
.setSmallIcon(icon)
.setVibrate(new long[] { 1000, 1000 })
.setLights(Color.BLUE, 700, 500)
.setContentTitle("Notification title")
.setStyle(new NotificationCompat.BigTextStyle().bigText(NorProv))
.addAction(R.mipmap.ic_autorenew_black_24dp, "New quote", piReload)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentText(Prov)
.build();
NotificationManager nMN = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nMN.notify(NOTIFICATION_ID, notification);
}

You can't do that, once a notification is sent you cannot change it's content
take a look at ANDROID NOTIFICATIONS

Related

Notification not showing in android Oreo when I use .setStyle

When creating a notification in android Oreo everything works until I use .setStyle then it stops working
Code:
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
int importance = NotificationManager.IMPORTANCE_HIGH;
{
NotificationChannel mChannel = new NotificationChannel(
CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, importance);
assert notificationManager != null;
notificationManager.createNotificationChannel(mChannel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle(track.getTitle())
.setContentText(track.getArtist())
.setSmallIcon(R.drawable.icon)
.setOnlyAlertOnce(true)//show notification for only first time
.setLights(Color.CYAN, 500, 1200) //Setting the color of the led blink on the phone for notifications
.addAction(drw_previous, "Previous", pendingIntentPrevious) //Setting action for the previous button
.addAction(playbutton, "Play", pendingIntentPlay) //Setting the action for the play/pause button
.addAction(drw_next, "Next", pendingIntentNext) //Setting the action for he next button
.setDeleteIntent(pendingIntentDelete) //Setting delete intent for when the notification is destroyed/deleted
.setStyle(new androidx.media.app.NotificationCompat.MediaStyle()
.setShowActionsInCompactView(0, 1, 2)
.setMediaSession(mediaSessionCompat.getSessionToken())) //Setting how and what order the buttons will be shown
.setShowWhen(false) //Do not show time for when this notification was created
.setDefaults(Notification.DEFAULT_ALL); //Defaults
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(intent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
notificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
}
Am I missing something. I have everything that should make it work. It used to work, but I am revisiting code changing it and making it better and not sure what went wrong this time. Your help is appreciated!

Action icon added in notification not showing up

I am trying to create a notification for Incoming call. For that I have added two actions in notification. My action text only is displayed.Action icon is not displayed in notification.
I want to add icon near Answer and cancel which I added as AddAction in Notification. I have added action icon like below,
NotificationCompat.Action answerAction = new NotificationCompat.Action.Builder(R.drawable.answer_call_icon, "Answer", pendingIntent).build();
NotificationCompat.Action cancelAction = new NotificationCompat.Action.Builder(R.drawable.cancel, "Cancel", pendingIntent).build();
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setLargeIcon((BitmapFactory.decodeResource(getResources(), R.drawable.call_logo)))
.setContentTitle(intent.getStringExtra("Number"))
.setSmallIcon(R.drawable.call_logo)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setFullScreenIntent(pendingIntent, true)
.setCategory(NotificationCompat.CATEGORY_CALL)
.addAction(answerAction)
.addAction(cancelAction)
.setPriority(NotificationCompat.PRIORITY_HIGH);
NotificationManagerCompat nManager = NotificationManagerCompat.from(this);
nManager.notify(2,builder.build());
One more query,
Below is my notification channnel,
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_HIGH);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.FLAG_FOREGROUND_SERVICE);
chan.setImportance(NotificationManager.IMPORTANCE_HIGH);
chan.setSound(defaultRingToneUri,audioAttributes);
chan.enableLights(true);
chan.shouldShowLights();
chan.setVibrationPattern(vibrate);
chan.enableVibration(true);
Context context=getApplicationContext();
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
Not able to get ringtone while receiving notification. Is the way Im setting sound is right??
Anybody please help me to solve this...
Posted 2 days ago..but till now not able to find solution.
As per the Notifications in Android N blog post:
Notification actions have also received a redesign and are now in a visually separate bar below the notification.
You’ll note that the icons are not present in the new notifications; instead more room is provided for the labels themselves in the constrained space of the notification shade. However, the notification action icons are still required and continue to be used on older versions of Android and on devices such as Android Wear.
So it is expected that you do not see the icons associated with notification actions.
If you need more flexibility in creating the notification layout, go for the custom one.
Ref: https://developer.android.com/training/notify-user/custom-notification
Use the Drawable left/right option to set an icon with text in the button.
// Get the layouts to use in the custom notification
RemoteViews notificationLayout = new RemoteViews(getPackageName(), R.layout.notification_small);
RemoteViews notificationLayoutExpanded = new RemoteViews(getPackageName(), R.layout.notification_large);
// Apply the layouts to the notification
Notification customNotification = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
.setCustomContentView(notificationLayout)
.setCustomBigContentView(notificationLayoutExpanded)
.build();
As I understand: you have a problem with your notification you can use this method :
private void showSmallNotification(NotificationCompat.Builder mBuilder, int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) {
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.addLine(message);
Notification notification;
notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
.setAutoCancel(true)
.setContentTitle(title)
.setContentIntent(resultPendingIntent)
.setSound(alarmSound)
.setStyle(inboxStyle)
.setWhen(getTimeMilliSec(timeStamp))
.setContentText(message)
.build();
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(Constant.NOTIFICATION_ID, notification);
}
or this one :
private void showBigNotification(Bitmap bitmap, NotificationCompat.Builder mBuilder, int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) {
NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
bigPictureStyle.setBigContentTitle(title);
bigPictureStyle.setSummaryText(Html.fromHtml(message).toString());
bigPictureStyle.bigPicture(bitmap);
Notification notification;
notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
.setAutoCancel(true)
.setContentTitle(title)
.setContentIntent(resultPendingIntent)
.setSound(alarmSound)
.setStyle(bigPictureStyle)
.setWhen(getTimeMilliSec(timeStamp))
.setContentText(message)
.build();
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(Constant.NOTIFICATION_ID_BIG_IMAGE, notification);
}
To play ringtone you can make use of android mediaplayer as shown below:
Var _mediaPlayer = MediaPlayer.Create(this,
Android.Provider.Settings.System.DefaultRingtoneUri);
_mediaPlayer.Start();
Task.Delay(60 * 1000).ContinueWith(t => _mediaPlayer?.Stop()); //stop after 60sec
You can take the global instance of _mediaPlayer and stop this as per user interaction with notification.
This is the c# xamarin android example, you can use the same class with java syntax.

Android: Notification that requires user interaction / input

I'm programming some Android App that must make some Notification/Alarm after event occurs. Im wondering is there any function for NotificationManager like requireInteraction()?
Now when the certain event occurs the app just shows one notification for 1 sec, that's it..i'd like user to click OK to stop this vibration/sound
I found some code for notification from here:
NotificationCompat.Builder deprecated in Android O
Thanks #Mehul
public void showNotification (String from, String notification,
Intent intent) {
int requestID = (int) System.currentTimeMillis();
PendingIntent pendingIntent = PendingIntent.getActivity(
context,
requestID,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
);
String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_DEFAULT);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
Notification mNotification = builder
.setContentTitle(from)
.setContentText(notification)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.build();
notificationManager.notify(/*notification id*/requestID, mNotification);
}
This one shows notification and it doesnt wait for user Input
If there is a need to add the buttons or action after clicking on notification you can use in your builder:
To add an button:
.addAction(new NotificationCompat.Action(*icon*, "Title", *intent for notification*));
or to add action that happen after user click the notification
.setContentIntent(*intent*);
Check the documentation about tab action and actions if you need more details.

How do I get the program to display multiple notifications on the screen?

i cant seem to understand how to display multiple notifications without one overlaying another. In my case it only displays one at the time.
picture 1
My goal is to get it to work like on the screenshot below
picture 2
What should I change or maybe add to my code?
chunk of code assigned for notifications
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
Intent intent = new Intent(ctx, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("com.example.romanchuk.appisode.notifyId", id);
intent.putExtra("com.example.romanchuk.appisode.show_id", show_id);
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, sNotificationId /* Request code */, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.addLine(message);
NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
bigText.bigText(message);
bigText.setBigContentTitle(getString(R.string.app_name));
NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx);
Notification notification = null;
notification = builder.setSmallIcon(R.mipmap.ic_launcher).setTicker(title).setWhen(0)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setColor(getResources().getColor(R.color.color_accent))
.setContentTitle("Appisode")
.setContentIntent(pendingIntent)
.setFullScreenIntent(pendingIntent, true)
.setContentText(message)
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setStyle(inboxStyle)
.setSmallIcon(R.drawable.small_icon)
.setSound(defaultSoundUri).build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(sNotificationId++, notification);
}
If you want to show multiple notifications, You Notification id should be different, If the notification id already exists in the notifications it will override that notification.
notificationManager.notify(sNotificationId++, notification);
In this sNotificationId should be different for all notification
If your id or show_id is int and not constant and if it will be different for each notification you can use that also as notification id.
Or try to give different tag for each notification like this,
notificationManager.notify(String.valueOf(System.currentTimeMillis()), sNotificationId++, notification);

I created pages in notification, the code shows no error but in wear, not showing me any pages

I created pages in notification, the code shows no error but in wear, not showing me any pages....Here's the code :
int notificationId = 001;
// Build intent for notification content
Intent viewIntent = new Intent(this, MainActivity.class);
viewIntent.putExtra("Helllo", "Hello Wear !");
PendingIntent viewPendingIntent =
PendingIntent.getActivity(this, 0, viewIntent, 0);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("My App")
.setContentText("Hello Wear !")
.setContentIntent(viewPendingIntent);
// Get an instance of the NotificationManager service
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(this);
// Build the notification and issues it with notification manager.
notificationManager.notify(notificationId, notificationBuilder.build());
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
// Create builder for the main notification
NotificationCompat.Builder notificationCompatBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Page 1")
.setContentText("Short message")
.setContentIntent(viewPendingIntent);
// Create a big text style for the second page
BigTextStyle secondPageStyle = new NotificationCompat.BigTextStyle();
secondPageStyle.setBigContentTitle("Page 2")
.bigText("A lot of text...");
// Create second page notification
Notification secondPageNotification =
new NotificationCompat.Builder(this)
.setStyle(secondPageStyle)
.build();
// Create main notification and add the second page
Notification twoPageNotification =
new WearableNotifications.Builder(notificationBuilder)
.addPage(secondPageNotification)
.build();
The code shows now error and runs fine, but is showing one page only instead of two.
Does the one-page-notification you get show "My App" / "Hello Wear !"?
This would be logical, because you are building this notification (var notificationBuilder) and actually have it displayed (notificationManager.notify()).
For the two-page notification, you create the first and second page - but when merging the first and the second page into twoPageNotification, you are using notificationBuilder instead of notificationCompatBuilder for your first page.
Additionally, that built, two-page notification twoPageNotification is never passed to the notify() function. So adding a notificationManager.notify(notificationId,twoPageNotification) should display those two pages.

Categories

Resources