Exemple #1
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);
        }
        /// <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());
            }
        }
        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);
            }));
        }
Exemple #4
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);
            }
        }
            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());
            }
        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());
            }
        }