예제 #1
0
        /// <summary>
        ///     Main logic for notification rendering
        /// </summary>
        /// <param name="icon">Lagge notification icon</param>
        /// <param name="title">Title of notification</param>
        /// <param name="message">Body of notification</param>
        /// <param name="resultPendingIntent">Intent action on notification click</param>
        private void ShowSmallNotification(Bitmap icon, string title, string message, PendingIntent resultPendingIntent)
        {
            var notificationManager = (NotificationManager)GetSystemService(NotificationService);
            var inboxStyle          = new NotificationCompat.InboxStyle();

            inboxStyle.AddLine(message);

            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                var channel = new NotificationChannel(ChannelId, ChannelName, NotificationImportance.High);
                channel.EnableVibration(true);
                channel.EnableLights(true);
                channel.SetShowBadge(true);
                notificationManager.CreateNotificationChannel(channel);
            }

            var notificationBuilder = new NotificationCompat.Builder(ApplicationContext, ChannelId)
                                      .SetVibrate(new long[] { 0, 100 })
                                      .SetAutoCancel(true)
                                      .SetContentTitle(title)
                                      .SetContentIntent(resultPendingIntent)
                                      .SetSmallIcon(Resource.Mipmap.ic_launcher)
                                      .SetStyle(inboxStyle)
                                      .SetLargeIcon(icon)
                                      .SetContentText(message);

            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                notificationBuilder.SetChannelId(ChannelId);
            }

            notificationManager.Notify(ChannelId, 1, notificationBuilder.Build());
        }
        /// <summary>
        /// Display the notification
        /// </summary>
        /// <param name="messageBody"></param>
        /// <param name="url"></param>
        private void DisplayNotification(string messageBody, string url)
        {
            int          notificationId = DateTime.Now.Millisecond;
            const int    SUMMARY_ID     = 9999;
            const string GROUP_ID       = "com.weavymessenger.droid.NOTIFICATIONS";
            var          intent         = new Intent(this, typeof(MainActivity));

            intent.PutExtra("url", url);

            intent.AddFlags(ActivityFlags.ClearTop);
            var pendingIntent = PendingIntent.GetActivity(this, DateTime.Now.Millisecond, intent, PendingIntentFlags.OneShot);

            // custom notification sound
            string pathToPushSound = $"android.resource://{ApplicationContext.PackageName}/raw/{Resource.Raw.notification}";

            global::Android.Net.Uri soundUri = global::Android.Net.Uri.Parse(pathToPushSound);
            var builder = new NotificationCompat.Builder(this, Constants.CHANNEL_ID)
                          .SetSmallIcon(Resource.Drawable.ic_notification)
                          .SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.ic_launcher))
                          .SetContentTitle(Helpers.Constants.DisplayName)
                          .SetContentText(messageBody)
                          .SetGroup(GROUP_ID)
                          .SetSound(soundUri)
                          .SetPriority((int)NotificationPriority.High)
                          .SetDefaults((int)NotificationDefaults.Vibrate)
                          .SetAutoCancel(true)
                          .SetVisibility((int)NotificationVisibility.Public)
                          .SetContentIntent(pendingIntent);

            NotificationManagerCompat notificationManager = NotificationManagerCompat.From(this);

            notificationManager.Notify(notificationId, builder.Build());


            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.N)
            {
                //Call API supported by Nougat and above, but not by lower API's

                var inbox = new NotificationCompat.InboxStyle();
                inbox.SetSummaryText("You have new messages");
                inbox.SetBigContentTitle(Helpers.Constants.DisplayName);
                var summaryNotification = new NotificationCompat.Builder(this, Constants.CHANNEL_ID)
                                          .SetContentTitle(Helpers.Constants.DisplayName)

                                          .SetContentText("You have new messages")
                                          .SetSmallIcon(Resource.Drawable.ic_notification)
                                          .SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.ic_launcher))
                                          //build summary info into InboxStyle template
                                          .SetStyle(inbox)

                                          //specify which group this notification belongs to
                                          .SetGroup(GROUP_ID)
                                          //set this notification as the summary for the group
                                          .SetGroupSummary(true);

                notificationManager.Notify(SUMMARY_ID, summaryNotification.Build());
            }
        }
예제 #3
0
        private void SendNotification(string title, string body, int id)
        {
            Intent intent = new Intent(this, typeof(NotificationActivity));

            intent.PutExtra("main_message", "This message is sent from MainActivity.cs!");
            PendingIntent pendingIntent =
                PendingIntent.GetActivity(this, 1, intent, PendingIntentFlags.OneShot);

            NotificationCompat.BigPictureStyle bigImage = new NotificationCompat.BigPictureStyle();
            bigImage.BigPicture(BitmapFactory.DecodeResource(Resources, Resource.Drawable.Xamarin));
            //NotificationCompat = class which defines all the metadata of the
            //                      notifications to be created -> styles, creation of object builder

            //NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
            //bigText.BigText("This is a super super super super super super super super\n" +
            //    "super super super super super super super super large text.....");
            //bigText.SetSummaryText("a super giant TEXT");
            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
            inboxStyle.SetSummaryText("An image from Xamarin.Android");
            //bigPicture.BigLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.ic_launcher_round));
            inboxStyle.SetBigContentTitle("This is the Big Content Title");
            inboxStyle.SetSummaryText("This is the summary text");
            inboxStyle.AddLine("Line 1");
            inboxStyle.AddLine("Line 2");
            inboxStyle.AddLine("Line 3");
            inboxStyle.AddLine("Line 4");
            inboxStyle.AddLine("Line 5");
            NotificationCompat.Builder builder =
                new NotificationCompat.Builder(this, CHANNEL_ID)
                .SetStyle(inboxStyle)
                .SetCategory(Notification.CategoryMessage)
                .SetContentIntent(pendingIntent)
                .SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.ic_launcher_round))
                .SetContentTitle(title)
                .SetContentText(body)
                .SetSmallIcon(Resource.Drawable.ic_launcher_round)
                .SetDefaults((int)(NotificationDefaults.Sound | NotificationDefaults.Vibrate))
                .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Alarm));

            Notification notificationObject = builder.Build();

            // notificationObject.Defaults |= NotificationDefaults.All;
            // set more notification metadata even when notification object is created

            var notificationManager = (NotificationManager)GetSystemService(NotificationService);

            notificationManager.Notify(id, notificationObject);
        }
예제 #4
0
            //###########################################

            public NotificationCompat.InboxStyle GetInbox()
            {
                var inbox = new NotificationCompat.InboxStyle();

                if (_type == NotifySettingsType.ONLY_FEED ||
                    _type == NotifySettingsType.FEED_AND_SHIFTS ||
                    _type == NotifySettingsType.FEED_AND_SHIFTS_AND_VERSIONS)
                {
                    if (_newFeed.Count > 10)
                    {
                        inbox.AddLine(_newFeed.Count + " " + _context.GetString(Resource.String.app_notify_msg_feed));
                    }
                    else
                    {
                        foreach (var item in _newFeed)
                        {
                            inbox.AddLine(item);
                        }
                    }
                }

                if (_type == NotifySettingsType.ONLY_SHIFTS ||
                    _type == NotifySettingsType.FEED_AND_SHIFTS ||
                    _type == NotifySettingsType.SHIFTS_AND_VERSIONS ||
                    _type == NotifySettingsType.FEED_AND_SHIFTS_AND_VERSIONS)
                {
                    foreach (var item in _newShifts)
                    {
                        inbox.AddLine(item);
                    }
                }

                if (_type == NotifySettingsType.SHIFTS_AND_VERSIONS ||
                    _type == NotifySettingsType.FEED_AND_SHIFTS_AND_VERSIONS)
                {
                    foreach (var item in _newShiftsVersion)
                    {
                        inbox.AddLine(item);
                    }
                }

                return(inbox);
            }
        public Task NotifyBigAsync(string v1, string v2, CompactWorldEvent theEvent, string theTime)
        {
            //return Task.CompletedTask;

            return(Task.Factory.StartNew(() =>
            {
                NotificationCompat.Builder builder = new NotificationCompat.Builder(_context, CHANNEL_ID)
                                                     .SetSmallIcon(Resource.Drawable.planetside2logo)
                                                     .SetContentTitle(v1)
                ;

                // Instantiate the Big Text style:
                //Notification.BigTextStyle textStyle = new Notification.BigTextStyle();
                NotificationCompat.InboxStyle textStyle = new NotificationCompat.InboxStyle();

                //fill with text
                textStyle.AddLine(v2);
                textStyle.AddLine($"Started at {theTime}");


                // Set the summary text:
                textStyle.SetSummaryText(v1);

                // Plug this style into the builder:
                builder.SetStyle(textStyle);

                Notification notification = builder.Build();

                // Get the notification manager:
                NotificationManager notificationManager =
                    _context.GetSystemService(Context.NotificationService) as NotificationManager;

                if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop)
                {
                    builder.SetVisibility(NotificationCompat.VisibilityPublic);
                }

                // Publish the notification:
                int notificationId = 0;
                notificationManager.Notify(notificationId, notification);
            }));
        }
예제 #6
0
        public static void ShowNotification(Context context, string channelID, string title, string msg, string address, string ticker, int notifId, int unreadCnt)
        {
            var intent = new Intent(context, typeof(DialogueActivity));

            intent.PutExtra("address", address);
            PendingIntent dialogueActivityIntent = PendingIntent.GetActivity(context, 0, intent, PendingIntentFlags.UpdateCurrent);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelID)
                                                 .SetContentTitle(title)
                                                 .SetContentText(msg)
                                                 .SetTicker(ticker)
                                                 .SetDefaults((int)NotificationDefaults.Sound | (int)NotificationDefaults.Vibrate)
                                                 .SetVisibility((int)NotificationVisibility.Public)
                                                 .SetPriority((int)NotificationPriority.High)
                                                 .SetVibrate(new long[] { 0, 1000, 500, 1000 })
                                                 .SetFullScreenIntent(dialogueActivityIntent, true)
                                                 .SetLargeIcon(BitmapFactory.DecodeResource(context.Resources, Resource.Drawable.ic_notification))
                                                 .SetSmallIcon(Resource.Drawable.ic_notification)
                                                 .SetCategory(Notification.CategoryMessage)
                                                 .SetColor(Application.Context.Resources.GetColor(Resource.Color.colorPrimary))
                                                 .SetAutoCancel(true)                                                                   //알림 클릭시 알림 아이콘이 상단바에서 사라짐.
                                                 .SetNumber(unreadCnt)
                                                                                                                                        //.AddAction(Resource.Drawable.dd9_send_36dp_2x_2, "답장", dialogueActivityIntent)
                                                                                                                                        //.AddAction(Resource.Drawable.dd9_send_36dp_2x_2, "읽음", dialogueActivityIntent)
                                                 .SetLights(Application.Context.Resources.GetColor(Resource.Color.colorPrimary), 1, 1); //LED 표시

            //확장 메시지
            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(builder);

            foreach (string elem in msg.Split('\n'))
            {
                inboxStyle.AddLine(elem);
            }
            inboxStyle.SetSummaryText("더 보기");
            builder.SetStyle(inboxStyle);

            NotificationManagerCompat notificationManager = NotificationManagerCompat.From(context);

            notificationManager.Notify(notifId, builder.Build());
        }
        private static void PopulateNotificationDayBeforeWithItems(NotificationCompat.Builder builder, BaseViewItemHomeworkExam[] items)
        {
            if (items.Length == 1)
            {
                builder.SetContentText(items[0].Name);
            }

            else
            {
                builder.SetContentText(items.Length + " items");
                var inboxStyle = new NotificationCompat.InboxStyle();
                for (int i = 0; i < 5 && i < items.Length; i++)
                {
                    inboxStyle.AddLine(items[i].Name);
                }
                if (items.Length > 5)
                {
                    inboxStyle.SetSummaryText("+" + (items.Length - 5) + " more");
                }
                builder.SetStyle(inboxStyle);
            }
        }
예제 #8
0
        private void btnSendNotificationWithInboxStyle_OnClick(object sender, EventArgs eventArgs)
        {
            // Specify the 'big view' content to display the long
            var inboxStyle = new NotificationCompat.InboxStyle();

            inboxStyle
            .AddLine("Line1")
            .AddLine("Line2")
            .AddLine("Line3")
            .AddLine("Line4")
            .SetBigContentTitle("Big Content Tilte")
            .SetSummaryText("+3 more");


            var builder = new NotificationCompat.Builder(Context);

            builder.SetContentTitle("Notification")
            .SetContentText("With Inbox Style")
            .SetLocalOnly(false)
            .SetSmallIcon(Resource.Drawable.icon8)
            .SetStyle(inboxStyle);

            NotificationManagerCompat.From(Context).Notify(117, builder.Build());
        }
            private void Update(Context context, Conversation conversation, IMessage message)
            {
                string messagesString = mMessages.GetString(conversation.Id.ToString(), null);

                if (messagesString == null)
                {
                    return;
                }

                // Get current notification texts
                IDictionary <long, string> positionText = new Dictionary <long, string>();

                try {
                    JSONObject messagesJson = new JSONObject(messagesString);
                    IIterator  iterator     = messagesJson.Keys();
                    while (iterator.HasNext)
                    {
                        string     messageId   = (string)iterator.Next();
                        JSONObject messageJson = messagesJson.GetJSONObject(messageId);
                        long       position    = messageJson.GetLong(KEY_POSITION);
                        string     text        = messageJson.GetString(KEY_TEXT);
                        positionText[position] = text;
                    }
                } catch (JSONException e) {
                    if (Util.Log.IsLoggable(Util.Log.ERROR))
                    {
                        Util.Log.e(e.Message, e);
                    }
                    return;
                }

                // Sort by message position
                List <long> positions = new List <long>(positionText.Keys);

                positions.Sort();

                // Construct notification
                string conversationTitle = AtlasUtil.GetConversationTitle(App.GetLayerClient(), App.GetParticipantProvider(), conversation);

                NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle().SetBigContentTitle(conversationTitle);
                int i;

                if (positions.Count <= MAX_MESSAGES)
                {
                    i = 0;
                    inboxStyle.SetSummaryText((string)null);
                }
                else
                {
                    i = positions.Count - MAX_MESSAGES;
                    inboxStyle.SetSummaryText(context.GetString(Resource.String.notifications_num_more, i));
                }
                while (i < positions.Count)
                {
                    inboxStyle.AddLine(positionText[positions[i++]]);
                }

                string collapsedSummary = positions.Count == 1 ? positionText[positions[0]] :
                                          context.GetString(Resource.String.notifications_new_messages, positions.Count);

                // Construct notification
                // TODO: use large icon based on avatars
                var mBuilder = new NotificationCompat.Builder(context)
                               .SetSmallIcon(Resource.Drawable.notification)
                               .SetContentTitle(conversationTitle)
                               .SetContentText(collapsedSummary)
                               .SetAutoCancel(true)
                               .SetLights(ContextCompat.GetColor(context, Resource.Color.atlas_action_bar_background), 100, 1900)
                               .SetPriority(NotificationCompat.PriorityHigh)
                               .SetDefaults(NotificationCompat.DefaultSound | NotificationCompat.DefaultVibrate)
                               .SetStyle(inboxStyle);

                // Intent to launch when clicked
                Intent clickIntent = new Intent(context, typeof(MessagesListActivity))
                                     .SetPackage(context.ApplicationContext.PackageName)
                                     .PutExtra(LAYER_CONVERSATION_KEY, conversation.Id)
                                     .PutExtra(LAYER_MESSAGE_KEY, message.Id)
                                     .SetFlags(ActivityFlags.ClearTop);
                PendingIntent clickPendingIntent = PendingIntent.GetActivity(
                    context, Interlocked.Increment(ref sPendingIntentCounterFlag),
                    clickIntent, PendingIntentFlags.OneShot);

                mBuilder.SetContentIntent(clickPendingIntent);

                // Intent to launch when swiped out
                Intent cancelIntent = new Intent(ACTION_CANCEL)
                                      .SetPackage(context.ApplicationContext.PackageName)
                                      .PutExtra(LAYER_CONVERSATION_KEY, conversation.Id)
                                      .PutExtra(LAYER_MESSAGE_KEY, message.Id);
                PendingIntent cancelPendingIntent = PendingIntent.GetBroadcast(
                    context, Interlocked.Increment(ref sPendingIntentCounterFlag),
                    cancelIntent, PendingIntentFlags.OneShot);

                mBuilder.SetDeleteIntent(cancelPendingIntent);

                // Show the notification
                mManager.Notify(conversation.Id.ToString(), MESSAGE_ID, mBuilder.Build());
            }
예제 #10
0
        public void OnReceived(IDictionary <string, object> parameters)
        {
            System.Diagnostics.Debug.WriteLine($"{DomainTag} - OnReceived");

            if (parameters.TryGetValue(SilentKey, out object silent) && (silent.ToString() == "true" || silent.ToString() == "1"))
            {
                return;
            }

            int notifyId        = 0;
            int summaryNotifyId = 786;

            string title   = context.ApplicationInfo.LoadLabel(context.PackageManager);
            var    message = string.Empty;
            var    tag     = string.Empty;
            var    image   = string.Empty;

            if (!string.IsNullOrEmpty(FirebasePushNotificationManager.NotificationContentTextKey) && parameters.TryGetValue(FirebasePushNotificationManager.NotificationContentTextKey, out object notificationContentText))
            {
                message = notificationContentText.ToString();
            }
            else if (parameters.TryGetValue(AlertKey, out object alert))
            {
                message = $"{alert}";
            }
            else if (parameters.TryGetValue(BodyKey, out object body))
            {
                message = $"{body}";
            }
            else if (parameters.TryGetValue(MessageKey, out object messageContent))
            {
                message = $"{messageContent}";
            }
            else if (parameters.TryGetValue(SubtitleKey, out object subtitle))
            {
                message = $"{subtitle}";
            }
            else if (parameters.TryGetValue(TextKey, out object text))
            {
                message = $"{text}";
            }

            if (!string.IsNullOrEmpty(FirebasePushNotificationManager.NotificationContentTitleKey) && parameters.TryGetValue(FirebasePushNotificationManager.NotificationContentTitleKey, out object notificationContentTitle))
            {
                title = notificationContentTitle.ToString();
            }
            else if (parameters.TryGetValue(TitleKey, out object titleContent))
            {
                if (!string.IsNullOrEmpty(message))
                {
                    title = $"{titleContent}";
                }
                else
                {
                    message = $"{titleContent}";
                }
            }

            if (parameters.TryGetValue(IdKey, out object id))
            {
                try {
                    notifyId = Convert.ToInt32(id);
                } catch (Exception ex) {
                    // Keep the default value of zero for the notify_id, but log the conversion problem.
                    System.Diagnostics.Debug.WriteLine($"Failed to convert {id} to an integer {ex}");
                }
            }

            if (parameters.TryGetValue(TagKey, out object tagContent))
            {
                tag = tagContent.ToString();
            }

            if (parameters.TryGetValue(ImageKey, out object imageContent))
            {
                image = imageContent.ToString();
            }

            try {
                if (parameters.TryGetValue(IconKey, out object icon) && icon != null)
                {
                    try {
                        FirebasePushNotificationManager.IconResource = context.Resources.GetIdentifier(icon.ToString(), "drawable", Application.Context.PackageName);
                    } catch (Resources.NotFoundException ex) {
                        System.Diagnostics.Debug.WriteLine(ex.ToString());
                    }
                }

                if (FirebasePushNotificationManager.IconResource == 0)
                {
                    FirebasePushNotificationManager.IconResource = context.ApplicationInfo.Icon;
                }
                else
                {
                    string name = context.Resources.GetResourceName(FirebasePushNotificationManager.IconResource);
                    if (name == null)
                    {
                        FirebasePushNotificationManager.IconResource = context.ApplicationInfo.Icon;
                    }
                }
            } catch (Resources.NotFoundException ex) {
                FirebasePushNotificationManager.IconResource = context.ApplicationInfo.Icon;
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }

            if (parameters.TryGetValue(ColorKey, out object color) && color != null)
            {
                try {
                    FirebasePushNotificationManager.Color = Color.ParseColor(color.ToString());
                } catch (Exception ex) {
                    System.Diagnostics.Debug.WriteLine($"{DomainTag} - Failed to parse color {ex}");
                }
            }

            Intent resultIntent = typeof(Activity).IsAssignableFrom(FirebasePushNotificationManager.NotificationActivityType) ? new Intent(Application.Context, FirebasePushNotificationManager.NotificationActivityType) : (FirebasePushNotificationManager.DefaultNotificationActivityType == null ? context.PackageManager.GetLaunchIntentForPackage(context.PackageName) : new Intent(Application.Context, FirebasePushNotificationManager.DefaultNotificationActivityType));

            Bundle extras = new Bundle();

            foreach (var p in parameters)
            {
                extras.PutString(p.Key, p.Value.ToString());
            }

            if (extras != null)
            {
                extras.PutInt(ActionNotificationIdKey, notifyId);
                extras.PutString(ActionNotificationTagKey, tag);
                resultIntent.PutExtras(extras);
            }

            if (FirebasePushNotificationManager.NotificationActivityFlags != null)
            {
                resultIntent.SetFlags(FirebasePushNotificationManager.NotificationActivityFlags.Value);
            }
            int requestCode = new Java.Util.Random().NextInt();

            var notificationStr = appPreferences.GetNotifications();
            List <NotificationModel> notificationList = JsonConvert.DeserializeObject <List <NotificationModel> >(notificationStr);

            notificationList.Add(new NotificationModel {
                NotifiyId = notifyId,
                Title     = title,
                Message   = message
            });
            appPreferences.SaveNotification(notificationList);

            var pendingIntent = PendingIntent.GetActivity(context, requestCode, resultIntent, PendingIntentFlags.UpdateCurrent);
            var deleteIntent  = new Intent(context, typeof(PushNotificationDeletedReceiver));

            deleteIntent.PutExtras(extras);

            var pendingDeleteIntent = PendingIntent.GetBroadcast(context, requestCode, deleteIntent, PendingIntentFlags.CancelCurrent);

            var chanId = FirebasePushNotificationManager.DefaultNotificationChannelId;

            if (parameters.TryGetValue(ChannelIdKey, out object channelId) && channelId != null)
            {
                chanId = $"{channelId}";
            }

            // Image Notification
            if (!string.IsNullOrEmpty(image))
            {
                URL    url    = new URL(image);
                Bitmap bitmap = BitmapFactory.DecodeStream(url.OpenConnection().InputStream);

                NotificationCompat.BigPictureStyle notifyImageStyle = new NotificationCompat.BigPictureStyle();
                notifyImageStyle.BigPicture(bitmap);
                notifyImageStyle.BigLargeIcon(bitmap);

                var notification = new NotificationCompat.Builder(context, chanId)
                                   .SetSmallIcon(FirebasePushNotificationManager.IconResource)
                                   .SetContentTitle(title)
                                   .SetContentText(message)
                                   .SetStyle(notifyImageStyle)
                                   .SetAutoCancel(true)
                                   .SetDefaults((int)NotificationDefaults.Lights)
                                   .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification))
                                   .SetContentIntent(pendingIntent)
                                   .SetDeleteIntent(pendingDeleteIntent);

                SetNotificationPriority(notification, parameters);
                ResolveLocalizedParameters(notification, parameters);
                SetNotificationAction(notification, parameters, extras);
                OnBuildNotification(notification, parameters);

                if (CrossFirebaseEssentials.Notifications.CanShowNotification)
                {
                    notificationManager.Notify(104, notification.Build());
                }
                return;
            }

            // Group Notification
            string groupKey  = string.Format("{0}{1}", context.ApplicationInfo.LoadLabel(context.PackageManager), "Notification");
            var    groupList = notificationList.GroupBy(x => x.Title).ToList();

            for (int i = 0; i < groupList.Count; i++)
            {
                var lstNotification = groupList[i].ToList();
                NotificationCompat.InboxStyle notifyInboxStyle = new NotificationCompat.InboxStyle();

                foreach (var item in lstNotification)
                {
                    notifyInboxStyle.AddLine(item.Message);
                }

                var notification = new NotificationCompat.Builder(context, chanId)
                                   .SetSmallIcon(FirebasePushNotificationManager.IconResource)
                                   .SetContentTitle(groupList[i].Key)
                                   .SetContentText(lstNotification.LastOrDefault().Message)
                                   .SetStyle(notifyInboxStyle)
                                   .SetAutoCancel(true)
                                   .SetGroup(groupKey)
                                   .SetDefaults((int)NotificationDefaults.Lights)
                                   .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification))
                                   .SetContentIntent(pendingIntent)
                                   .SetDeleteIntent(pendingDeleteIntent);

                SetNotificationPriority(notification, parameters);
                ResolveLocalizedParameters(notification, parameters);
                SetNotificationAction(notification, parameters, extras);
                OnBuildNotification(notification, parameters);

                if (CrossFirebaseEssentials.Notifications.CanShowNotification)
                {
                    notificationManager.Notify(i, notification.Build());
                }
            }

            NotificationCompat.InboxStyle summaryInboxStyle = new NotificationCompat.InboxStyle()
                                                              .SetSummaryText(string.Format("{0} new messages", groupList.Count))
                                                              .SetBigContentTitle(context.ApplicationInfo.LoadLabel(context.PackageManager));

            foreach (var item in groupList)
            {
                var lstNotification = item.ToList();
                summaryInboxStyle.AddLine(string.Format("{0} {1}", item.Key, lstNotification.LastOrDefault().Message));
            }

            var summaryNotification = new NotificationCompat.Builder(context, chanId)
                                      .SetSmallIcon(FirebasePushNotificationManager.IconResource)
                                      .SetAutoCancel(true)
                                      .SetStyle(summaryInboxStyle)
                                      .SetGroup(groupKey)
                                      .SetGroupAlertBehavior(NotificationCompat.GroupAlertChildren)
                                      .SetGroupSummary(true)
                                      .SetDefaults((int)NotificationDefaults.Lights)
                                      .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification))
                                      .SetContentIntent(pendingIntent)
                                      .SetDeleteIntent(pendingDeleteIntent);

            SetNotificationPriority(summaryNotification, parameters);
            ResolveLocalizedParameters(summaryNotification, parameters);
            SetNotificationAction(summaryNotification, parameters, extras);
            OnBuildNotification(summaryNotification, parameters);

            if (CrossFirebaseEssentials.Notifications.CanShowNotification)
            {
                notificationManager.Notify(summaryNotifyId, summaryNotification.Build());
            }
        }
예제 #11
0
        public void IssueNotification()
        {
            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                //create Notification Channel
                NotificationChannel channel = new NotificationChannel(MyConstants.CHANNEL_ID, MyConstants.CHANNEL_NAME, NotificationImportance.High);
                channel.EnableVibration(true);
                channel.SetVibrationPattern(
                    new long[]
                    { 500, 500, 500, 500 });
                //set visibility on lockscreen
                channel.LockscreenVisibility = NotificationVisibility.Public;


                //create the channel
                NotificationManager manager = Android.App.Application.Context.GetSystemService(Context.NotificationService) as NotificationManager;
                manager.CreateNotificationChannel(channel);

                //set an action to tske the user to the active activity when user clicks on notification
                Intent intent = new Intent(Android.App.Application.Context, typeof(MainActivity));
                intent.AddCategory(Intent.CategoryLauncher);
                intent.SetAction(Intent.ActionMain);

                //create pendingIntent
                PendingIntent pendingIntent = PendingIntent.GetActivity(Android.App.Application.Context, 1, intent, 0);


                //build the notification
                var builder = new NotificationCompat.Builder(Android.App.Application.Context, MyConstants.CHANNEL_ID);
                builder.SetContentTitle("This is the Notification Title")
                .SetContentText("Testing Notification right now!")
                .SetSmallIcon(Resource.Drawable.ic_mr_button_grey)
                .SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis())
                .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Ringtone))
                .SetContentIntent(pendingIntent)
                .SetLargeIcon(BitmapFactory.DecodeResource(Android.App.Application.Context.Resources, Resource.Drawable.user));

                //create big text style notification in the expanded. This class does not support method chaining
                //you have to explitcitely use the NotificationBuilder object to call the BigTextStyle class
                //NotificationCompat.BigTextStyle bigtext = new NotificationCompat.BigTextStyle();
                //string gibberish = "This is the new big text style notification";
                //gibberish += "/and we are just testing it";
                //bigtext.BigText(gibberish);
                //bigtext.SetSummaryText("This is just a summary");
                ////push BigText into builder for the notification
                //builder.SetStyle(bigtext);

                ////used to create image notification
                //NotificationCompat.BigPictureStyle picturestyle = new NotificationCompat.BigPictureStyle();
                //picturestyle.BigPicture(BitmapFactory.DecodeResource(Android.App.Application.Context.Resources, Resource.Drawable.bsplash));
                //builder.SetStyle(picturestyle);

                //used to create an inbox type of email
                NotificationCompat.InboxStyle inboxstyle = new NotificationCompat.InboxStyle();
                inboxstyle.AddLine("Temilayo: I am waiting at the park")
                .AddLine("Marko: The Tesla is ready for pickup")
                .AddLine("Honey 2: Our flight is in 20 mins")
                .SetSummaryText("+3 more");

                builder.SetStyle(inboxstyle);


                //Notification.SetPriority(NotificationPriority.High);
                //.build the notification
                Notification notification = builder.Build();
                //issue the Notification
                NotificationManager manager2 = NotificationManager.FromContext(Android.App.Application.Context);
                manager2.Notify(MyConstants.NOTIFICATION_ID, notification);
            }

            else
            {
                //set an action to tske the user to the active activity when user clicks on notification
                Intent intent = new Intent(Android.App.Application.Context, typeof(MainActivity));
                //intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop);
                intent.SetAction(Intent.ActionMain);
                intent.AddCategory(Intent.CategoryLauncher);
                //create pendingIntent
                PendingIntent pendingIntent = PendingIntent.GetActivity(Android.App.Application.Context, 2, intent, 0);

                var notification = new NotificationCompat.Builder(Android.App.Application.Context, MyConstants.CHANNEL_ID_2);
                notification.SetContentTitle("This is the other notification")
                .SetContentText("This is the body of the other notification")
                .SetSmallIcon(Resource.Drawable.ic_audiotrack_dark)
                .SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis())
                .SetContentIntent(pendingIntent)
                .SetLargeIcon(BitmapFactory.DecodeResource(Android.App.Application.Context.Resources, Resource.Drawable.smallicon));

                //create big text style notification in the expanded. This class does not support method chaining
                //you have to explitcitely use the NotificationBuilder object to call the BigTextStyle class

                NotificationCompat.BigTextStyle bigtext = new NotificationCompat.BigTextStyle();
                string gibberish = "This is the new big text style notification";
                gibberish += "/and we are just testing it";
                bigtext.BigText(gibberish);
                bigtext.SetSummaryText("This is just a summary");
                //push BigText into builder for the notification
                notification.SetStyle(bigtext);
                notification.SetPriority(NotificationCompat.PriorityMax);

                ////used to create image notification
                //NotificationCompat.BigPictureStyle picturestyle = new NotificationCompat.BigPictureStyle();
                //picturestyle.BigPicture(BitmapFactory.DecodeResource(Android.App.Application.Context.Resources, Resource.Drawable.bsplash));
                //notification.SetStyle(picturestyle);

                //used to create an inbox type of email
                NotificationCompat.InboxStyle inboxstyle = new NotificationCompat.InboxStyle();
                inboxstyle.AddLine("Temilayo: I am waiting at the park")
                .AddLine("Marko: The Tesla is ready for pickup")
                .AddLine("Honey 2: Our flight is in 20 mins")
                .SetSummaryText("+3 more");

                notification.SetStyle(inboxstyle);

                Notification        Notiffy  = notification.Build();
                NotificationManager manager3 = NotificationManager.FromContext(Android.App.Application.Context);
                manager3.Notify(MyConstants.NOTIFICATION_ID_2, Notiffy);
            }
        }
        public static async Task CreateNotifications(LocationData location, List <WeatherAlert> alerts)
        {
            // Gets an instance of the NotificationManager service
            NotificationManagerCompat mNotifyMgr = NotificationManagerCompat.From(App.Context);

            InitChannel();

            // Create click intent
            // Start WeatherNow Activity with weather data
            Intent intent = new Intent(App.Context, typeof(MainActivity))
                            .SetAction(Widgets.WeatherWidgetService.ACTION_SHOWALERTS)
                            .PutExtra("data", location.ToJson())
                            .PutExtra(Widgets.WeatherWidgetService.ACTION_SHOWALERTS, true)
                            .SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask | ActivityFlags.ClearTask);
            PendingIntent clickPendingIntent = PendingIntent.GetActivity(App.Context, 0, intent, 0);

            // Build update
            foreach (WeatherAlert alert in alerts)
            {
                var alertVM = new WeatherAlertViewModel(alert);

                var iconBmp = ImageUtils.TintBitmap(
                    await BitmapFactory.DecodeResourceAsync(App.Context.Resources, GetDrawableFromAlertType(alertVM.AlertType)),
                    Color.Black);

                var title = String.Format("{0} - {1}", alertVM.Title, location.name);

                NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(App.Context, NOT_CHANNEL_ID)
                    .SetSmallIcon(Resource.Drawable.ic_error_white)
                    .SetLargeIcon(iconBmp)
                    .SetContentTitle(title)
                    .SetContentText(alertVM.ExpireDate)
                    .SetStyle(new NotificationCompat.BigTextStyle().BigText(alertVM.ExpireDate))
                    .SetContentIntent(clickPendingIntent)
                    .SetOnlyAlertOnce(true)
                    .SetAutoCancel(true)
                    .SetPriority(NotificationCompat.PriorityDefault) as NotificationCompat.Builder;

                if (Build.VERSION.SdkInt < BuildVersionCodes.N)
                {
                    // Tell service to remove stored notification
                    mBuilder.SetDeleteIntent(GetDeleteNotificationIntent((int)alertVM.AlertType));
                }

                if (Build.VERSION.SdkInt >= BuildVersionCodes.N ||
                    WeatherAlertNotificationService.GetNotificationsCount() >= MIN_GROUPCOUNT)
                {
                    mBuilder.SetGroup(TAG);
                }

                // Builds the notification and issues it.
                // Tag: location.query; id: weather alert type
                if (Build.VERSION.SdkInt < BuildVersionCodes.N)
                {
                    WeatherAlertNotificationService.AddNotication((int)alertVM.AlertType, title);
                }
                mNotifyMgr.Notify(location.query, (int)alertVM.AlertType, mBuilder.Build());
            }

            bool buildSummary = false;

            if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
            {
                try
                {
                    NotificationManager mNotifyMgrV23 = (NotificationManager)App.Context.GetSystemService(App.NotificationService);
                    var statNotifs = mNotifyMgrV23.GetActiveNotifications();

                    if (statNotifs?.Length > 0)
                    {
                        buildSummary = statNotifs.Count(not => location.query.Equals(not.Tag)) >= MIN_GROUPCOUNT;
                    }
                }
                catch (Exception ex)
                {
                    Logger.WriteLine(LoggerLevel.Debug, ex, "SimpleWeather: {0}: error accessing notifications", LOG_TAG);
                }
            }
            else
            {
                buildSummary = WeatherAlertNotificationService.GetNotificationsCount() >= MIN_GROUPCOUNT;
            }

            if (buildSummary)
            {
                // Notification inboxStyle for grouped notifications
                var inboxStyle = new NotificationCompat.InboxStyle();

                if (Build.VERSION.SdkInt < BuildVersionCodes.N)
                {
                    // Add active notification titles to summary notification
                    foreach (var notif in WeatherAlertNotificationService.GetNotifications())
                    {
                        mNotifyMgr.Cancel(location.query, notif.Key);
                        inboxStyle.AddLine(notif.Value);
                    }

                    inboxStyle.SetBigContentTitle(App.Context.GetString(Resource.String.title_fragment_alerts));
                    inboxStyle.SetSummaryText(location.name);
                }
                else
                {
                    inboxStyle.SetSummaryText(App.Context.GetString(Resource.String.title_fragment_alerts));
                }

                NotificationCompat.Builder mSummaryBuilder =
                    new NotificationCompat.Builder(App.Context, NOT_CHANNEL_ID)
                    .SetSmallIcon(Resource.Drawable.ic_error_white)
                    .SetContentTitle(App.Context.GetString(Resource.String.title_fragment_alerts))
                    .SetContentText(location.name)
                    .SetStyle(inboxStyle)
                    .SetGroup(TAG)
                    .SetGroupSummary(true)
                    .SetContentIntent(clickPendingIntent)
                    .SetOnlyAlertOnce(true)
                    .SetAutoCancel(true) as NotificationCompat.Builder;

                if (Build.VERSION.SdkInt < BuildVersionCodes.N)
                {
                    mSummaryBuilder.SetDeleteIntent(GetDeleteAllNotificationsIntent());
                }

                // Builds the summary notification and issues it.
                mNotifyMgr.Notify(location.query, SUMMARY_ID, mSummaryBuilder.Build());
            }
        }