I have implemented the push notification using FCM in my xamarin forms android project. When I tap on the notification I will show the corresponding content page also.
My code for showing the notification on UI using notificationBuilder
public void SendNotificatios(string body, string Header)
{
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
var notificationBuilder = new NotificationCompat.Builder(this)
.SetContentTitle(Header)
.SetSmallIcon(Resource.Drawable.icon)
.SetContentText(body)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent);
var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
notificationManager.Notify(0, notificationBuilder.Build());
//notificationManager.Notify(new Random().Next(), notificationBuilder.Build());
}
else
{
var notificationBuilder = new NotificationCompat.Builder(this, Utils.CHANNEL_ID)
.SetContentTitle(Header)
.SetSmallIcon(Resource.Drawable.icon)
.SetContentText(body)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent);
var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
NotificationChannel channel = new NotificationChannel(Utils.CHANNEL_ID, "FCM Notifications", NotificationImportance.Default);
notificationManager.CreateNotificationChannel(channel);
notificationManager.Notify(0, notificationBuilder.Build());
//notificationManager.Notify(new Random().Next(), notificationBuilder.Build());
}
}
I have implemented the notification tapping like below:
MainActivity:
//Background or killed mode
if (Intent.Extras != null)
{
foreach (var key in Intent.Extras.KeySet())
{
var value = Intent.Extras.GetString(key);
Log.Debug(TAG, "Key: {0} Value: {1}", key, value);
if (key == "webContentList") // Make it Dynamic instead of hardcoding here
{
if (value?.Length > 0)
{
isNotification = true;
LoadApplication(new App(value));
}
}
}
}
//Foreground mode
if (FirebaseNotificationService.webContentList.ToString() != "")
{
isNotification = true;
LoadApplication(new App(FirebaseNotificationService.webContentList.ToString()));
FirebaseNotificationService.webContentList = "";
}
//Normal loading
if (!isNotification)
{
LoadApplication(new App(string.Empty));
}
On App.xaml.cs:
public App(string domain, string isNotification)
{
//Notification tapping section
if ((!String.IsNullOrEmpty(isNotification) && isNotification?.Length > 0) || _webContentList != null)
{
_webContentList = JsonConvert.DeserializeObject<List<webContentList>>(isNotification);
MainPage = new DashBoardPage(_webContentList[0],null, isGroup);//loading the corresponsing page
}
else if (domain == "")//normal loading
{
MainPage = new SmartWCM.MainPage(domain, false);
}
}
Currently, only one notification will show on the phone. The new notifications will clear the old one and the last notification will show on the UI. This is happening because I have set 0 as the value inside notificationManager.Notify.
notificationManager.Notify(0, notificationBuilder.Build());
If I change it like a random number like below all notification will show on UI.
notificationManager.Notify(new Random().Next(), notificationBuilder.Build());
My problem at this stage(when multiple notifications are visible on UI) how I can implement the notifications tapping? If I click any notification only the last notifications corresponding page will open. Any solution for this.
Related
I set a notification for a player, I want to update icon after play or pause action from notification.
This is my code for Notification.
private void showNotification(String title, Bitmap bitmap) {
//region Create Notification
MediaSessionCompat mediaSession = new MediaSessionCompat(getApplicationContext(), "session tag");
MediaSessionCompat.Token token = mediaSession.getSessionToken();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this,"PRIMARY_CHANNEL")
.setSmallIcon(R.mipmap.ic_launcher_1)
.setLargeIcon(bitmap)
.setContentTitle("Simplay")
.setContentText(title)
.setOngoing(true)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentIntent(notifyPendingIntent)
.addAction(R.drawable.exo_controls_rewind,"",rewindPendingIntent)
**.addAction( R.drawable.exo_controls_pause,"",playPendingIntent)**
.addAction(R.drawable.exo_controls_fastforward,"",forwardPendingIntent)
.setStyle(new android.support.v4.media.app.NotificationCompat.MediaStyle()
.setMediaSession(token))
.setPriority(NotificationCompat.PRIORITY_HIGH);
notificationManager = NotificationManagerCompat.from(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Notification";
String description = "";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel("PRIMARY_CHANNEL", name, importance);
channel.setDescription(description);
channel.enableLights(true);
channel.setShowBadge(false);
channel.setLockscreenVisibility(123);
NotificationManager notificationManager1 = getSystemService(NotificationManager.class);
notificationManager1.createNotificationChannel(channel);
}
notificationManager.notify(123, mBuilder.build());
//endregion
}
You should use
.addAction(getResources.getDrawable(R.drawable.exo_controls_pause),"",playPendingIntent)
Solution
To change the icon of action at realtime, you need:
Get and replace action.
Push new notification.
For example:
notificationBuilder.actions[1] = new Notification.Action(R.drawable.pause, "play", pendingIntent);
NotificationManager service = ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE));
service.notify(101, notificationBuilder);
or
notificationBuilder.actions[1] = new Notification.Action(R.drawable.pause, "play", pendingIntent);
startForeground(101, notificationBuilder);
The best solution I've found is basically to remove all actions from builder and add them again, then resubmit the notification.
(code in Kotlin)
fun startNotification()
{
_builder = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)
.setContentText("Title")
.setContentIntent(_contentIntent)
.setOngoing(true)
updateNotification(true) // set initial playing state here
}
fun updateNotification(playing: Boolean)
{
val playPauseResource = if (playing) R.drawable.pause else R.drawable.play
_builder
.clearActions()
.addAction(R.drawable.prev, "Rewind", _rewindPendingIntent)
.addAction(playPauseResource, "Play/pause", _playPendingIntent)
.addAction(R.drawable.next, "Next", _forwardPendingIntent)
with(NotificationManagerCompat.from(_context))
{
notify(NOTIFICATION_ID, _builder.build())
}
}
Push notification is not working on Android device having a version number 7.1.2, but working fine on version 9. Following is my code for showing the notification.
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
var notificationBuilder = new Android.App.Notification.Builder(this, Utils.CHANNEL_ID)
.SetContentTitle(Header)
.SetSmallIcon(Resource.Drawable.icon)
.SetContentText(body)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent);
var notificationManager = NotificationManager.FromContext(this);
notificationManager.Notify(0, notificationBuilder.Build());
}
else
{
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
var notificationBuilder = new Android.App.Notification.Builder(this, Utils.CHANNEL_ID)
.SetContentTitle(Header)
.SetSmallIcon(Resource.Drawable.icon)
.SetContentText(body)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent)
.SetChannelId(Utils.CHANNEL_ID);
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
return;
}
var channel = new NotificationChannel(Utils.CHANNEL_ID, "FCM Notifications", NotificationImportance.High)
{
Description = "Firebase Cloud Messages appear in this channel"
};
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.CreateNotificationChannel(channel);
notificationManager.Notify(0, notificationBuilder.Build());
}
Can anyone please suggest a solution for this?
I following this sample
https://learn.microsoft.com/en-us/azure/notification-hubs/xamarin-notification-hubs-push-notifications-android-gcm
I post my SendNotification method from my production project.
Following my working code and change your method.
void SendNotification (string messageBody, string title)
{
var intent = new Intent (this, typeof (SplashActivity));
intent.AddFlags (ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity (this, 0, intent, PendingIntentFlags.OneShot);
//if i want more than one notification ,different unique value in every call
Random u = new Random ();
if (Build.VERSION.SdkInt >= BuildVersionCodes.O) {
string channelName = Resources.GetString (Resource.String.channel_name);
NotificationCompat.Builder notificationBuilder;
notificationBuilder = new NotificationCompat.Builder (this, channelName)
.SetContentTitle (title)
.SetSmallIcon (Resource.Drawable.ic_stat_g)
.SetContentText (messageBody)
.SetAutoCancel (true)
.SetContentIntent (pendingIntent);
var notificationManager = GetSystemService (Context.NotificationService) as NotificationManager;
NotificationChannel channel = new NotificationChannel (channelName, "notification channel", NotificationImportance.Default);
notificationManager.CreateNotificationChannel (channel);
notificationManager.Notify (u.Next(), notificationBuilder.Build ());
}
else
{
NotificationCompat.Builder notificationBuilder;
notificationBuilder = new NotificationCompat.Builder (this)
.SetContentTitle (title)
.SetSmallIcon (Resource.Drawable.ic_stat_g)
.SetContentText (messageBody)
.SetAutoCancel (true)
.SetContentIntent (pendingIntent);
var notificationManager = GetSystemService (Context.NotificationService) as NotificationManager;
notificationManager.Notify (u.Next(), notificationBuilder.Build ());
}
}
First of all don't use Android.App.Notification.Builder is deprecated. The NotificationCompat.Builder is the new one.
Maybe this one is your new code
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
var notificationBuilder = new NotificationCompat.Builder(this)
.SetContentTitle(Header)
.SetSmallIcon(Resource.Drawable.icon)
.SetContentText(body)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent);
var notificationManager = GetSystemService (Context.NotificationService) as NotificationManager;
notificationManager.Notify(0, notificationBuilder.Build());
}
else
{
var notificationBuilder = new NotificationCompat.Builder(this, Utils.CHANNEL_ID)
.SetContentTitle(Header)
.SetSmallIcon(Resource.Drawable.icon)
.SetContentText(body)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent);
var notificationManager = GetSystemService (Context.NotificationService) as NotificationManager;
NotificationChannel channel = new NotificationChannel (Utils.CHANNEL_ID, "FCM Notifications", NotificationImportance.Default);
notificationManager.CreateNotificationChannel (channel);
notificationManager.Notify (0, notificationBuilder.Build ());
}
Firebase notifications behave differently depending on the foreground/background state of the receiving app.
Notification messages delivered when your app is in the background. In this case, the notification is delivered to the device’s system tray. A user tap on a notification opens the app launcher by default.
Messages with both notification and data payload, when received in the background. In this case, the notification is delivered to the device’s system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.
For more information, visit https://firebase.google.com/docs/cloud-messaging/android/receive
I also have this sample code for you to try:
var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
NotificationChannel notificationChannel = new NotificationChannel("my_channel", "This is my Notification Channel", NotificationImportance.High);
builder.SetChannelId("my_channel");
notificationManager.CreateNotificationChannel(notificationChannel);
}
var notification = builder.SetContentIntent(PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.Immutable))
.SetSmallIcon(Resource.Drawable.icon)
.SetContentTitle(Header)
.SetContentText(body)
//Set vibrate
.SetVibrate(new long[] { 200, 200, 200, 200 })
//LED
.SetLights(Android.Graphics.Color.Blue, 1000, 1000)
//Auto cancel will remove the notification once the user touches it
.SetAutoCancel(true).Build();
notificationManager.Notify(0, notification);
We have created an chat app with notifications using FCM my code is correct my device is getting the push notification data as well but some Chinese manufactured device like vivo, oppo, one plus, xiaomi are not allowing the notification to show unless i add app in protected app list of respective manufacturer. is their any solution for this.
https://hackernoon.com/notifications-in-android-are-horribly-broken-b8dbec63f48a
https://github.community/t5/Project-Development-Help-and/Firebase-Push-Notification-not-receiving-on-some-android-devices/td-p/5489
private NotificationManagerCompat notificationManager;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d("test","call");
notificationManager = NotificationManagerCompat.from(this);
sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
}
private void sendNotification(String title, String msg) {
Intent resultIntent = new Intent(this, ActivitySplashScreen.class);
String channelId = getString(R.string.chc);
String channelName = "Message Notification";
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntentWithParentStack(resultIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(99, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle(title)
.setContentText(msg)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setContentIntent(pendingIntent)
.build();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationManager manager = getSystemService(NotificationManager.class);
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
manager.createNotificationChannel(channel);
}
notificationManager.notify(10, notification);
}
I can confirm that this implementation works well with One Plus and Xiaomi devices (we have plenty of users using our app from this devices, and no crashes or issues are created from them regarding FCM Notifications).
Cannot confirm anything for Vivo or Oppo (so far, we do know we don't have users using this kind of devices).
The most important thing is that the notification feature is well implemented if regarding the app is either in foreground or background. If someone wants to do a zoom on this matter, this article explains it on a easy way.
Now, the code I use for FCM implementation in Android:
//MyMessagingService
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public static final String TAG = "Firebase Msg";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> data = remoteMessage.getData();
final LocalNotification localNotification = new LocalNotification();
//data --> entityId - entityType - pushNotificationType
// Check if message contains a data payload.
if (data.size() > 0) {
localNotification.setEntityId(data.get("entityId"));
localNotification.setEntityType(data.get("entityType"));
localNotification.setPushNotificationType(data.get("pushNotificationType"));
localNotification.setTitle(data.get("title"));
localNotification.setBody(data.get("body"));
localNotification.setIcon(data.get("icon"));
localNotification.setDate(new Date().getTime());
localNotification.setRead(false);
}
if (localNotification.getEntityId() != null) {
LocalNotification notificationRetrieved = FirebaseNotificationsHelper.insertLocalNotification(localNotification);
FirebaseNotificationsHelper.createNotificationInStatus(notificationRetrieved);
}
}
}
//Create notification status
static void createNotificationInStatus(LocalNotification localNotification) {
String notificationChannelId = App.getContext().getString(R.string.default_notification_channel_id);
String notificationChannelName = App.getContext().getString(R.string.default_notification_channel_name);
String notificationChannelDescription = App.getContext().getString(R.string.default_notification_channel_description);
NotificationCompat.Builder notificationBuilder;
NotificationCompat.Builder notificationBuilderPublicVersion;
notificationBuilder = new NotificationCompat.Builder(App.getContext(), notificationChannelId);
notificationBuilderPublicVersion = new NotificationCompat.Builder(App.getContext(), notificationChannelId);
notificationBuilder.setDefaults(NotificationCompat.DEFAULT_VIBRATE | NotificationCompat.DEFAULT_LIGHTS | NotificationCompat.DEFAULT_SOUND)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_stat_push_notif)
.setTicker(localNotification.getTitle())
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentTitle(localNotification.getTitle())
.setContentText(localNotification.getBody())
.setStyle(new NotificationCompat.BigTextStyle().bigText(localNotification.getBody()))
.setPublicVersion(notificationBuilderPublicVersion.setSmallIcon(R.drawable.ic_stat_push_notif).setContentTitle(localNotification.getTitle()).
setWhen(System.currentTimeMillis()).setContentText(localNotification.getBody()).build())
.setGroup(NOTIFICATION_GROUP)
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
.setAutoCancel(true);
int notificationId = SharedPreferencesUtils.getInstance(App.getContext()).getIntValue(PREF_KEY_NOTIFICATION_ID, 0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) App.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel notificationChannel = new NotificationChannel(notificationChannelId, notificationChannelName, NotificationManager.IMPORTANCE_HIGH);
// Configure the notification channel.
notificationChannel.setDescription(notificationChannelDescription);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
notificationChannel.setImportance(NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(notificationChannel);
notificationManager.notify(notificationId, notificationBuilder.build());
} else {
/* Kitkat and previous versions don't show notifications using NotificationManagerCompat */
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
NotificationManager notificationManager = (NotificationManager) App.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationId, notificationBuilder.build());
} else {
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(App.getContext());
notificationManager.notify(notificationId, notificationBuilder.build());
}
}
notificationId++;
SharedPreferencesUtils.getInstance(App.getContext()).setValue(PREF_KEY_NOTIFICATION_ID, notificationId);
}
I donot think that there is a general solution for this since your app is based on google-FCM that means that the android device regularly comunicates with google-internet-services.
As far as i know google-FCM is blocked (= not reachable) in china
I am trying to group notifications and trigger sounds only for some of them using notification builder setSound() method, but it doesn't work. Each time I receive notifications it triggers the ringtone even though I call setSound(null)
This is my code:
TaskStackBuilder stackBuilder = TaskStackBuilder.create(getContext());
stackBuilder.addParentStack(getParentActivityClass());
Intent notificationIntent = intent == null ? new Intent() : new Intent(intent);
if (cls != null)
notificationIntent.setClass(getContext(), cls);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
stackBuilder.addNextIntentWithParentStack(notificationIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
InboxStyle style = new NotificationCompat.InboxStyle();
int mapId = subGroupId + groupId;
putGroupLine(mapId, text);
List<String> notifLines = groupedNotificationsMap.get(mapId);
for (int i = 0; i < notifLines.size(); i++) {
style.addLine(notifLines.get(i));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String NOTIFICATION_CHANNEL_ID = "default";
String channelName = "Default";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName
, NotificationManager.IMPORTANCE_HIGH);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
if (alert == false) {
chan.setSound(null, null);
chan.setVibrationPattern(null);
}
else {
chan.setVibrationPattern(vibrate);
}
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.createNotificationChannel(chan);
}
NotificationCompat.Builder mBuilder;
mBuilder = new NotificationCompat.Builder(context, "default")
.setSmallIcon(getSmallIconResource())
.setAutoCancel(true);
int colorRes = getSmallIconColor();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mBuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY);
}
if (alert) {
mBuilder.setSound(getRingtone());
mBuilder.setVibrate( vibrate );
}
else {
mBuilder.setSound(null);
mBuilder.setVibrate(null);
}
Notification notif = mBuilder
.setContentTitle(title)
.setTicker(text)
.setContentText(text)
.setSmallIcon(getSmallIconResource())
.setStyle(style
.setBigContentTitle(title)
)
.setGroup("g" + groupId)
.setContentIntent(pendingIntent)
.build();
NotificationCompat.Builder summaryBiulder = new NotificationCompat.Builder(getContext(), "default")
.setContentTitle(title)
.setAutoCancel(true)
//set content text to support devices running API level < 24
.setContentText(text)
.setSmallIcon(getSmallIconResource())
//build summary info into InboxStyle template
.setStyle(new InboxStyle()
.setBigContentTitle(title)
.setSummaryText(title))
.setColor(colorRes)
//specify which group this notification belongs to
.setGroup("g" + groupId)
//set this notification as the summary for the group
.setGroupSummary(true)
.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY)
.setContentIntent(pendingIntent);
if (alert) {
summaryBiulder.setSound(getRingtone());
summaryBiulder.setVibrate( vibrate );
}
else {
summaryBiulder.setSound(null);
summaryBiulder.setVibrate(null);
}
Notification summaryNotification = summaryBiulder .build();
notif.flags |= Notification.FLAG_AUTO_CANCEL;
notif.flags |= Notification.FLAG_HIGH_PRIORITY;
notifManager.notify(subGroupId, notif);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notifManager.notify(groupId, summaryNotification);
}
Any suggestions?
Your problem is about notification importance
importance types
IMPORTANCE_MAX: unused
IMPORTANCE_HIGH: shows everywhere, makes noise and peeks
IMPORTANCE_DEFAULT: shows everywhere, makes noise, but does not visually intrude
IMPORTANCE_LOW: shows everywhere, but is not intrusive
IMPORTANCE_MIN: only shows in the shade, below the fold
IMPORTANCE_NONE: a notification with no importance; does not show in the shade
source
Although the other answers are useful, the main issue here was that the notification channel was already created. So, as stated in the docs, the behavior of a channel cannot be changed after creation (sound and vibration in this case). Only name and description can be changed, the user has full control over the rest.
In the code snippet,
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName,
NotificationManager.IMPORTANCE_HIGH);
Try replacing
NotificationManager.IMPORTANCE_HIGH to NotificationManager.IMPORTANCE_NONE
As according to Android developer documentation,
IMPORTANCE_HIGH
Higher notification importance: shows everywhere, makes noise and peeks. May use full screen intents.
So it may be making sound due to this.
Here's the link to other importance values available
I am generating local notification with multiple lines. All lines are showing properly but contentTitle and contentText are not showing.
Here is my code to generate a notification:
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(notificationIntent);
int num = (int) System.currentTimeMillis();
PendingIntent pendingIntent = stackBuilder.getPendingIntent(num, PendingIntent.FLAG_UPDATE_CURRENT);
String id = "notification_channel_id";
CharSequence name = "Message_Notification";
Bitmap bm = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, id)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("title")
.setContentText("time")
.setAutoCancel(true)
.setGroupSummary(true)
.setGroup(GROUP_KEY)
.setContentIntent(pendingIntent)
.setChannelId(id);
if (subTitle != null) {
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.setBigContentTitle("Dose Reminder");
if (subTitle.contains("---")) {
String[] splitStrings = subTitle.split("---");
for (int i = 0; i < splitStrings.length; i++) {
inboxStyle.addLine(splitStrings[i]);
}
} else {
inboxStyle.addLine(subTitle);
// Moves the expanded layout object into the notification object.
notificationBuilder.setStyle(inboxStyle);
}
// Moves the expanded layout object into the notification object.
notificationBuilder.setStyle(inboxStyle);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notificationBuilder.setColor(ContextCompat.getColor(context, R.color.colorAccent));
} else {
notificationBuilder.setLargeIcon(bm);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
// The user.-visible description of the channel.
String description = "Notifications contains messages which was sent by dev team.";
int importance = NotificationManager.IMPORTANCE_MAX;
NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_DEFAULT);
// Configure the notification channel.
mChannel.setDescription(description);
mChannel.enableLights(true);
// Sets the notification light color for notifications posted to this
// channel, if the device supports this feature.
mChannel.setLightColor(Color.RED);
if (notificationManager != null) {
notificationManager.createNotificationChannel(mChannel);
}
}
// Sets an ID for the notification
// Gets an instance of the NotificationManager service
final NotificationManager mNotifyMgr =
(NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
// Builds the notification and issues it.
if (mNotifyMgr != null) {
mNotifyMgr.notify(num, notificationBuilder.build());
}
When notification comes "title" and "time" are not showing. It showing "Dose Reminder" and subTitles in multiple lines.
Am I missing something?
setBigContentTitle(CharSequence title)
Overrides ContentTitle in the big form of the template.
https://developer.android.com/reference/android/app/Notification.InboxStyle
Check Use MessagingStyle section
https://developer.android.com/training/notify-user/build-notification
JFYI by default timestamp is gone in push notifications, Android 7 (Nougat) onwards