/// <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());
            }
        }
Esempio n. 2
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);
        }
        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());
            }
        }