Exemplo n.º 1
0
        NotificationCompat.Action BuildServiceAction(string action, string text, int icon, int requestCode)
        {
            var pendingIntent = BuildServicePendingIntent(action, requestCode);
            var builder       = new NotificationCompat.Action.Builder(icon, text, pendingIntent);

            return(builder.Build());
        }
Exemplo n.º 2
0
		private void OnButtonClick()
		{
			requestCode++;

			// Build PendingIntent
			var pendingIntent = MakePendingIntent();

			var replyText = GetString(Resource.String.reply_text);

			// Create remote input that will read text
			var remoteInput = new Android.Support.V4.App.RemoteInput.Builder(KEY_TEXT_REPLY)
										 .SetLabel(replyText)
										 .Build();

			// Build action for noticiation
			var action = new NotificationCompat.Action.Builder(Resource.Drawable.action_reply, replyText, pendingIntent)
											   .AddRemoteInput(remoteInput)
											   .Build();

			// Build notification
			var notification = new NotificationCompat.Builder(this)
													 .SetSmallIcon(Resource.Drawable.reply)
													 .SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.avatar))
													 .SetContentText("Hey, it is James! What's up?")
													 .SetContentTitle(GetString(Resource.String.message))
													 .SetAutoCancel(true)
													 .AddAction(action)
													 .Build();

			// Notify
			using (var notificationManager = NotificationManagerCompat.From(this))
			{
				notificationManager.Notify(requestCode, notification);
			}
		}
Exemplo n.º 3
0
        private void OnButtonClick()
        {
            requestCode++;

            // Build PendingIntent
            var pendingIntent = MakePendingIntent();

            var replyText = GetString(Resource.String.reply_text);

            // Create remote input that will read text
            var remoteInput = new Android.Support.V4.App.RemoteInput.Builder(KEY_TEXT_REPLY)
                              .SetLabel(replyText)
                              .Build();

            // Build action for noticiation
            var action = new NotificationCompat.Action.Builder(Resource.Drawable.action_reply, replyText, pendingIntent)
                         .AddRemoteInput(remoteInput)
                         .Build();

            // Build notification
            var notification = new NotificationCompat.Builder(this)
                               .SetSmallIcon(Resource.Drawable.reply)
                               .SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.avatar))
                               .SetContentText("Hey, it is James! What's up?")
                               .SetContentTitle(GetString(Resource.String.message))
                               .SetAutoCancel(true)
                               .AddAction(action)
                               .Build();

            // Notify
            using (var notificationManager = NotificationManagerCompat.From(this))
            {
                notificationManager.Notify(requestCode, notification);
            }
        }
Exemplo n.º 4
0
        private void btnSendNotificationWithVoiceInput_OnClick(object sender, EventArgs eventArgs)
        {
            // Key for the string that's delivered in the action's intent
            var replyChoices = new string[] { "Choice 1", "Choice 2" };
            var remoteInput  = new Android.Support.V4.App.RemoteInput.Builder(EXTRA_VOICE_REPLY)
                               .SetLabel("Reply")
                               .SetChoices(replyChoices)
                               .Build();


            // Build intent for notification content
            var pendingIntent = new Intent(Context, typeof(AndroidWearStep1ActivityExtraIntent));

            pendingIntent.PutExtra("EXTRA_EVENT_ID", 2);
            var viewPendingIntent = PendingIntent.GetActivity(Context, 0, pendingIntent, PendingIntentFlags.UpdateCurrent);

            // Create the reply action and add the remote input
            var action = new NotificationCompat.Action.Builder(Resource.Drawable.ic_media_play, "Reply!", viewPendingIntent)
                         .AddRemoteInput(remoteInput)
                         .Build();

            // Build the notification and add the action via WearableExtender
            var notification = new NotificationCompat.Builder(Context)
                               .SetSmallIcon(Resource.Drawable.icon9)
                               .SetContentTitle("Notification")
                               .SetContentText("With Voice Input Action")
                               .Extend(new NotificationCompat.WearableExtender().AddAction(action))
                               .Build();


            NotificationManagerCompat.From(Context).Notify(118, notification);
        }
        protected virtual NotificationCompat.Action CreateAction(Notification notification, ChannelAction action)
        {
            var pendingIntent = this.CreateActionIntent(notification, action);
            var iconId        = this.core.Android.GetResourceIdByName(action.Identifier);
            var nativeAction  = new NotificationCompat.Action.Builder(iconId, action.Title, pendingIntent).Build();

            return(nativeAction);
        }
        NotificationCompat.Action BuildAction(string ACTION, int drawableIcon, string caption)
        {
            var actionIntent = new Intent(this, GetType());

            actionIntent.SetAction(ACTION);
            var pendingIntent = PendingIntent.GetService(this, 0, actionIntent, 0);

            var builder = new NotificationCompat.Action.Builder(drawableIcon, caption, pendingIntent);

            return(builder.Build());
        }
        /// <summary>
        /// Builds a Notification.Action that will instruct the service to restart the timer.
        /// </summary>
        /// <returns>The restart timer action.</returns>
        NotificationCompat.Action BuildRestartTimerAction()
        {
            var restartTimerIntent = new Intent(this, GetType());

            restartTimerIntent.SetAction(Constants.ACTION_RESTART_TIMER);
            var restartTimerPendingIntent = PendingIntent.GetService(this, 0, restartTimerIntent, 0);

            var builder = new NotificationCompat.Action.Builder(Resource.Drawable.ic_action_restart_timer,
                                                                GetText(Resource.String.restart_timer),
                                                                restartTimerPendingIntent);

            return(builder.Build());
        }
Exemplo n.º 8
0
        /// <summary>
        /// Builds the Notification.Action that will allow the user to stop the service via the
        /// notification in the status bar
        /// </summary>
        /// <returns>The stop service action.</returns>
        private NotificationCompat.Action BuildStopServiceAction()
        {
            Intent stopServiceIntent = new Intent(this, GetType());

            stopServiceIntent.SetAction(ActionStopService);
            Android.App.PendingIntent stopServicePendingIntent = Android.App.PendingIntent.GetService(this, 0, stopServiceIntent, 0);

            var builder = new NotificationCompat.Action.Builder(Resource.Drawable.ic_stat_cancel,
                                                                GetText(Resource.String.service_stop_comm),
                                                                stopServicePendingIntent);

            return(builder.Build());
        }
Exemplo n.º 9
0
        NotificationCompat.Action BuildStopServiceAction()
        {
            var stopServiceIntent = new Intent(this, GetType());

            stopServiceIntent.SetAction(Constants.ACTION_STOP_SERVICE);
            var stopServicePendingIntent = PendingIntent.GetService(this, 0, stopServiceIntent, 0);

            var builder = new NotificationCompat.Action.Builder(Android.Resource.Drawable.IcMediaPause,
                                                                GetText(Resource.String.action_disconnect),
                                                                stopServicePendingIntent);

            return(builder.Build());
        }
Exemplo n.º 10
0
        protected virtual NotificationCompat.Action CreateTextReply(Notification notification, NotificationAction action)
        {
            var pendingIntent = this.CreateActionIntent(notification, action);
            var input         = new RemoteInput.Builder("Result")
                                .SetLabel(action.Title)
                                .Build();

            var iconId       = this.context.GetResourceIdByName(action.Identifier);
            var nativeAction = new NotificationCompat.Action.Builder(iconId, action.Title, pendingIntent)
                               .SetAllowGeneratedReplies(true)
                               .AddRemoteInput(input)
                               .Build();

            return(nativeAction);
        }
Exemplo n.º 11
0
        protected virtual NotificationCompat.Action CreateTextReply(Notification notification, ChannelAction action)
        {
            var pendingIntent = this.CreateActionIntent(notification, action);
            var input         = new AndroidX.Core.App.RemoteInput.Builder(AndroidNotificationProcessor.RemoteInputResultKey)
                                .SetLabel(action.Title)
                                .Build();

            var iconId       = this.core.Android.GetResourceIdByName(action.Identifier);
            var nativeAction = new NotificationCompat.Action.Builder(iconId, action.Title, pendingIntent)
                               .SetAllowGeneratedReplies(true)
                               .AddRemoteInput(input)
                               .Build();

            return(nativeAction);
        }
Exemplo n.º 12
0
        public void notificar(Intent intent)
        {
            /*
             * var ongoing = new Notification(Resource.Drawable.navicon, "Radar+");
             * var pendingIntent = PendingIntent.GetActivity(this, 0, new Intent(this, typeof(MainActivity)), 0);
             * ongoing.SetLatestEventInfo(this, "Radar+", "Está em funcionamento", pendingIntent);
             * StartForeground((int)NotificationFlags.ForegroundService, ongoing);
             */
            if (intent.GetBooleanExtra("stop_service", false))
            {
                StopSelf();
            }
            else
            {
                Context context            = Android.App.Application.Context;
                Intent  notificationIntent = new Intent(this, typeof(GPSAndroid));
                notificationIntent.PutExtra("stop_service", true);
                //PendingIntent pendingIntent = PendingIntent.GetService(this, 0, notificationIntent, 0);
                //PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_ONE_SHOT);
                var acao = new Intent(context, typeof(BroadcastAndroid));
                acao.SetAction("Fechar");

                var pendingIntent = PendingIntent.GetBroadcast(context, 0, acao, PendingIntentFlags.UpdateCurrent);

                //Button
                NotificationCompat.Action action = new NotificationCompat.Action.Builder(Resource.Drawable.mystop, "Fechar", pendingIntent).Build();

                Notification notificacao = new NotificationCompat.Builder(context)
                                           .SetSmallIcon(Resource.Drawable.radarplus_logo)
                                           .SetContentTitle("Radar+")
                                           .SetContentText("Seu Radar+ está em funcionamento.")
                                           .SetAutoCancel(true)
                                           .SetPriority((int)NotificationPriority.Max)
                                           .AddAction(action) //add buton
                                           .Build();

                //notification.SetLatestEventInfo( this, "Radar+", "Pressione aqui para fechar.", pendingIntent);
                //StartForeground((int)NotificationFlags.ForegroundService, notification);

                NotificationManager notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService);
                //Notification notificacao = notification;
                //notificacao.Flags = NotificationFlags.AutoCancel;
                notificacao.Flags = NotificationFlags.NoClear;
                notificationManager.Notify(1, notificacao);
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Builds the Notification.Action that will allow the user to stop the service via the
        /// notification in the status bar
        /// </summary>
        /// <returns>The stop service action.</returns>
        private NotificationCompat.Action BuildStopServiceAction()
        {
            Intent stopServiceIntent = new Intent(this, GetType());

            stopServiceIntent.SetAction(ActionStopService);
            Android.App.PendingIntentFlags intentFlags = 0;
            if (Build.VERSION.SdkInt >= BuildVersionCodes.S)
            {
                intentFlags |= Android.App.PendingIntentFlags.Mutable;
            }
            Android.App.PendingIntent stopServicePendingIntent = Android.App.PendingIntent.GetService(this, 0, stopServiceIntent, intentFlags);

            var builder = new NotificationCompat.Action.Builder(Resource.Drawable.ic_stat_cancel,
                                                                GetText(Resource.String.service_stop_comm),
                                                                stopServicePendingIntent);

            return(builder.Build());
        }
Exemplo n.º 14
0
        public NotificationCompat.Action CreateAction(int icon, string title, string action, Action <NotificationCompat.Action.Builder> build = null)
        {
            var intent = new Intent(_context, typeof(RadioStationService)).SetAction(action);

            var flags = PendingIntentFlags.UpdateCurrent;

            if (action.Equals(RadioStationService.ActionStop))
            {
                flags = PendingIntentFlags.CancelCurrent;
            }

            var pendingIntent = PendingIntent.GetService(_context, 1, intent, flags);
            var builder       = new NotificationCompat.Action.Builder(icon, title, pendingIntent);

            build?.Invoke(builder);

            return(builder.Build());
        }
        public Notification BuildNotification(Service context, string channelId)
        {
            var piLaunchMainActivity = GetLaunchActivity(context);
            var stopService          = GetStopService(context);

            // Action to stop the service
            var stopAction = new NotificationCompat.Action.Builder(StopActionIcon, GetStopNotificationText, stopService).Build();

            // create notification
            var notification = new NotificationCompat.Builder(context, channelId).
                               SetContentTitle(GetNotificationTitle).
                               SetContentText(GetNotificationContext).
                               SetSmallIcon(SmallIcon).
                               SetContentIntent(piLaunchMainActivity).
                               AddAction(stopAction).
                               SetStyle(new NotificationCompat.BigTextStyle()).Build();

            return(notification);
        }
Exemplo n.º 16
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.Main);

            Button button = FindViewById <Button>(Resource.Id.MyButton);

            button.Click += delegate
            {
                // Wear の入力画面を構築
                // RemoteInput.Builder だと Android.RemoteInput と競合するのでフルで指定しています。
                // 正式な書き方は不明です。。
                var remoteInput = new Android.Support.V4.App.RemoteInput.Builder("Reply")
                                  .SetLabel(GetText(Resource.String.Reply)) // "Reply Label"
                                  .Build();
                // pendingIntent で起動する Activity
                var intent = new Intent(this, typeof(StartActionActivity));
                // Wear の Update を待つ処理
                var replyPendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.UpdateCurrent);
                // Wear でスワイプ (Extender?) した際のアクション
                var replyAction = new NotificationCompat.Action.Builder(
                    Android.Resource.Drawable.IcButtonSpeakNow,
                    GetText(Resource.String.Reply), replyPendingIntent)  // "リプライ"
                                  .AddRemoteInput(remoteInput)
                                  .Build();
                // Wear の Extender を構築
                var wealableExtender = new NotificationCompat.WearableExtender()
                                       .AddAction(replyAction);
                // Wear の Notification を構築
                var notificationBuilder = new NotificationCompat.Builder(this)
                                          .SetSmallIcon(Android.Resource.Drawable.IcDialogAlert)
                                          .SetContentTitle(GetText(Resource.String.AlertTitle))  // "アラート"
                                          .SetContentText(GetText(Resource.String.AlertMessage)) // "左にスワイプしてください"
                                          .Extend(wealableExtender);
                // Notification を送る Activity を指定
                var notificationManager = NotificationManagerCompat.From(this);
                // 実際に Notification を送る
                notificationManager.Notify(1, notificationBuilder.Build());
            };
        }
        public Notification BuildNotificationPreO(Service context)
        {
            var piLaunchMainActivity = GetLaunchActivity(context);
            var stopService          = GetStopService(context);


            // Action to stop the service
            NotificationCompat.Action stopAction = new NotificationCompat.Action.Builder(StopActionIcon, GetStopNotificationText, stopService).Build();

            if (Android.OS.Build.VERSION.SdkInt <= Android.OS.BuildVersionCodes.O)
            {
                // create notification
                var notification = new NotificationCompat.Builder(context).SetContentTitle(GetNotificationTitle)
                                   .SetContentText(GetNotificationContext).SetSmallIcon(SmallIcon)
                                   .SetContentIntent(piLaunchMainActivity).AddAction(stopAction)
                                   .SetStyle(new NotificationCompat.BigTextStyle()).Build();

                return(notification);
            }

            return(null);
        }
        void SendNotificationForConversation(Conversations.Conversation conversation)
        {
            // A pending Intent for reads
            PendingIntent readPendingIntent = PendingIntent.GetBroadcast(ApplicationContext,
                                                                         conversation.ConversationId,
                                                                         GetMessageReadIntent(conversation.ConversationId),
                                                                         PendingIntentFlags.UpdateCurrent);

            // Build a RemoteInput for receiving voice input in a Car Notification or text input on
            // devices that support text input (like devices on Android N and above).
            var remoteInput = new Android.Support.V4.App.RemoteInput.Builder(EXTRA_REMOTE_REPLY)
                              .SetLabel(GetString(Resource.String.reply))
                              .Build();

            // Building a Pending Intent for the reply action to trigger
            PendingIntent replyIntent = PendingIntent.GetBroadcast(ApplicationContext,
                                                                   conversation.ConversationId,
                                                                   GetMessageReplyIntent(conversation.ConversationId),
                                                                   PendingIntentFlags.UpdateCurrent);

            // Build an Android N compatible Remote Input enabled action.
            NotificationCompat.Action actionReplyByRemoteInput = new NotificationCompat.Action.Builder(
                Resource.Drawable.notification_icon,
                GetString(Resource.String.reply),
                replyIntent).AddRemoteInput(remoteInput).Build();

            // Create the UnreadConversation and populate it with the participant name,
            // read and reply intents.
            var unreadConvBuilder =
                new NotificationCompat.CarExtender.UnreadConversation.Builder(conversation.ParticipantName)
                .SetLatestTimestamp(conversation.Timestamp)
                .SetReadPendingIntent(readPendingIntent)
                .SetReplyAction(replyIntent, remoteInput);

            // Note: Add messages from oldest to newest to the UnreadConversation.Builder
            var messageForNotification = new StringBuilder();

            for (int i = 0; i < conversation.Messages.Count; i++)
            {
                unreadConvBuilder.AddMessage(conversation.Messages [i]);
                messageForNotification.Append(conversation.Messages [i]);
                if (i != conversation.Messages.Count - 1)
                {
                    messageForNotification.Append(EOL);
                }
            }

            NotificationCompat.Builder builder = new NotificationCompat.Builder(ApplicationContext)
                                                 .SetSmallIcon(Resource.Drawable.notification_icon)
                                                 .SetLargeIcon(BitmapFactory.DecodeResource(
                                                                   ApplicationContext.Resources, Resource.Drawable.android_contact))
                                                 .SetContentText(messageForNotification.ToString())
                                                 .SetWhen(conversation.Timestamp)
                                                 .SetContentTitle(conversation.ParticipantName)
                                                 .SetContentIntent(readPendingIntent)
                                                 .Extend(new NotificationCompat.CarExtender()
                                                         .SetUnreadConversation(unreadConvBuilder.Build())
                                                         .SetColor(ContextCompat.GetColor(this, Resource.Color.default_color_light)))
                                                 .AddAction(actionReplyByRemoteInput);

            MessageLogger.LogMessage(ApplicationContext, "Sending notification "
                                     + conversation.ConversationId + " conversation: " + conversation);

            mNotificationManager.Notify(conversation.ConversationId, builder.Build());
        }
Exemplo n.º 19
0
		void SendNotificationForConversation (Conversations.Conversation conversation)
		{
			// A pending Intent for reads
			PendingIntent readPendingIntent = PendingIntent.GetBroadcast (ApplicationContext,
				                                  conversation.ConversationId,
				                                  GetMessageReadIntent (conversation.ConversationId),
				                                  PendingIntentFlags.UpdateCurrent);

			// Build a RemoteInput for receiving voice input in a Car Notification or text input on
			// devices that support text input (like devices on Android N and above).
			var remoteInput = new Android.Support.V4.App.RemoteInput.Builder (EXTRA_REMOTE_REPLY)
				.SetLabel (GetString (Resource.String.reply))
				.Build ();

			// Building a Pending Intent for the reply action to trigger
			PendingIntent replyIntent = PendingIntent.GetBroadcast (ApplicationContext,
				                            conversation.ConversationId,
				                            GetMessageReplyIntent (conversation.ConversationId),
				                            PendingIntentFlags.UpdateCurrent);

			// Build an Android N compatible Remote Input enabled action.
			NotificationCompat.Action actionReplyByRemoteInput = new NotificationCompat.Action.Builder (
				Resource.Drawable.notification_icon,
				GetString (Resource.String.reply),
				replyIntent).AddRemoteInput (remoteInput).Build ();

			// Create the UnreadConversation and populate it with the participant name,
			// read and reply intents.
			var unreadConvBuilder =
				new NotificationCompat.CarExtender.UnreadConversation.Builder (conversation.ParticipantName)
					.SetLatestTimestamp (conversation.Timestamp)
					.SetReadPendingIntent (readPendingIntent)
					.SetReplyAction (replyIntent, remoteInput);

			// Note: Add messages from oldest to newest to the UnreadConversation.Builder
			var messageForNotification = new StringBuilder ();
			for (int i = 0; i < conversation.Messages.Count; i++) {
				unreadConvBuilder.AddMessage (conversation.Messages [i]);
				messageForNotification.Append (conversation.Messages [i]);
				if (i != conversation.Messages.Count - 1)
					messageForNotification.Append (EOL);
			}

			NotificationCompat.Builder builder = new NotificationCompat.Builder (ApplicationContext)
				.SetSmallIcon (Resource.Drawable.notification_icon)
				.SetLargeIcon (BitmapFactory.DecodeResource (
				                                     ApplicationContext.Resources, Resource.Drawable.android_contact))
				.SetContentText (messageForNotification.ToString ())
				.SetWhen (conversation.Timestamp)
				.SetContentTitle (conversation.ParticipantName)
				.SetContentIntent (readPendingIntent)
				.Extend (new NotificationCompat.CarExtender ()
					.SetUnreadConversation (unreadConvBuilder.Build ())
				         .SetColor (ContextCompat.GetColor (this, Resource.Color.default_color_light)))
				.AddAction (actionReplyByRemoteInput);

			MessageLogger.LogMessage (ApplicationContext, "Sending notification "
			+ conversation.ConversationId + " conversation: " + conversation);

			mNotificationManager.Notify (conversation.ConversationId, builder.Build ());
		}
        public virtual void OnReceived(IDictionary <string, object> parameters)
        {
            System.Diagnostics.Debug.WriteLine($"{DomainTag} - OnReceived");

            if ((parameters.TryGetValue(SilentKey, out var silent) && (silent.ToString() == "true" || silent.ToString() == "1")) || (IsInForeground() && (!(!parameters.ContainsKey(ChannelIdKey) && parameters.TryGetValue(PriorityKey, out var imp) && ($"{imp}" == "high" || $"{imp}" == "max")) || (!parameters.ContainsKey(PriorityKey) && !parameters.ContainsKey(ChannelIdKey) && PushNotificationManager.DefaultNotificationChannelImportance != NotificationImportance.High && PushNotificationManager.DefaultNotificationChannelImportance != NotificationImportance.Max))))
            {
                return;
            }

            Context context = Application.Context;

            var notifyId           = 0;
            var title              = context.ApplicationInfo.LoadLabel(context.PackageManager);
            var message            = string.Empty;
            var tag                = string.Empty;
            var notificationNumber = 0;
            var showWhenVisible    = PushNotificationManager.ShouldShowWhen;
            var soundUri           = PushNotificationManager.SoundUri;
            var largeIconResource  = PushNotificationManager.LargeIconResource;
            var smallIconResource  = PushNotificationManager.IconResource;
            var notificationColor  = PushNotificationManager.Color;
            var chanId             = PushNotificationManager.DefaultNotificationChannelId;

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

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

            if (parameters.TryGetValue(IdKey, out var 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(NumberKey, out var num))
            {
                try
                {
                    notificationNumber = Convert.ToInt32(num);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"Failed to convert {num} to an integer {ex}");
                }
            }

            if (parameters.TryGetValue(ShowWhenKey, out var shouldShowWhen))
            {
                showWhenVisible = $"{shouldShowWhen}".ToLower() == "true";
            }


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

            try
            {
                if (parameters.TryGetValue(SoundKey, out var sound))
                {
                    var soundName  = sound.ToString();
                    var soundResId = context.Resources.GetIdentifier(soundName, "raw", context.PackageName);
                    if (soundResId == 0 && soundName.IndexOf('.') != -1)
                    {
                        soundName  = soundName.Substring(0, soundName.LastIndexOf('.'));
                        soundResId = context.Resources.GetIdentifier(soundName, "raw", context.PackageName);
                    }

                    soundUri = new Android.Net.Uri.Builder()
                               .Scheme(ContentResolver.SchemeAndroidResource)
                               .Path($"{context.PackageName}/{soundResId}")
                               .Build();
                }
            }
            catch (Resources.NotFoundException ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }

            if (soundUri == null)
            {
                soundUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
            }
            try
            {
                if (parameters.TryGetValue(IconKey, out var icon) && icon != null)
                {
                    try
                    {
                        smallIconResource = context.Resources.GetIdentifier(icon.ToString(), "drawable", Application.Context.PackageName);
                        if (smallIconResource == 0)
                        {
                            smallIconResource = context.Resources.GetIdentifier($"{icon}", "mipmap", Application.Context.PackageName);
                        }
                    }
                    catch (Resources.NotFoundException ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex.ToString());
                    }
                }

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


            try
            {
                if (parameters.TryGetValue(LargeIconKey, out object largeIcon) && largeIcon != null)
                {
                    largeIconResource = context.Resources.GetIdentifier($"{largeIcon}", "drawable", Application.Context.PackageName);
                    if (largeIconResource == 0)
                    {
                        largeIconResource = context.Resources.GetIdentifier($"{largeIcon}", "mipmap", Application.Context.PackageName);
                    }
                }

                if (largeIconResource > 0)
                {
                    string name = context.Resources.GetResourceName(largeIconResource);
                    if (name == null)
                    {
                        largeIconResource = 0;
                    }
                }
            }
            catch (Resources.NotFoundException ex)
            {
                largeIconResource = 0;
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }

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

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

            var 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 (PushNotificationManager.NotificationActivityFlags != null)
            {
                resultIntent.SetFlags(PushNotificationManager.NotificationActivityFlags.Value);
            }
            var requestCode   = new Java.Util.Random().NextInt();
            var pendingIntent = PendingIntent.GetActivity(context, requestCode, resultIntent, PendingIntentFlags.UpdateCurrent);

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

            var notificationBuilder = new NotificationCompat.Builder(context, chanId)
                                      .SetSmallIcon(smallIconResource)
                                      .SetContentTitle(title)
                                      .SetContentText(message)
                                      .SetAutoCancel(true)
                                      .SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis())
                                      .SetContentIntent(pendingIntent);

            if (notificationNumber > 0)
            {
                notificationBuilder.SetNumber(notificationNumber);
            }

            if (Build.VERSION.SdkInt >= BuildVersionCodes.JellyBeanMr1)
            {
                notificationBuilder.SetShowWhen(showWhenVisible);
            }

            if (largeIconResource > 0)
            {
                Bitmap largeIconBitmap = BitmapFactory.DecodeResource(context.Resources, largeIconResource);
                notificationBuilder.SetLargeIcon(largeIconBitmap);
            }

            if (parameters.TryGetValue(FullScreenIntentKey, out var fullScreenIntent) && ($"{fullScreenIntent}" == "true" || $"{fullScreenIntent}" == "1"))
            {
                var fullScreenPendingIntent = PendingIntent.GetActivity(context, requestCode, resultIntent, PendingIntentFlags.UpdateCurrent);
                notificationBuilder.SetFullScreenIntent(fullScreenPendingIntent, true);
                notificationBuilder.SetCategory(NotificationCompat.CategoryCall);
                parameters[PriorityKey] = "high";
            }

            var deleteIntent = new Intent(context, typeof(PushNotificationDeletedReceiver));

            deleteIntent.PutExtras(extras);
            var pendingDeleteIntent = PendingIntent.GetBroadcast(context, requestCode, deleteIntent, PendingIntentFlags.UpdateCurrent);

            notificationBuilder.SetDeleteIntent(pendingDeleteIntent);

            if (Build.VERSION.SdkInt < BuildVersionCodes.O)
            {
                if (parameters.TryGetValue(PriorityKey, out var priority) && priority != null)
                {
                    var priorityValue = $"{priority}";
                    if (!string.IsNullOrEmpty(priorityValue))
                    {
                        switch (priorityValue.ToLower())
                        {
                        case "max":
                            notificationBuilder.SetPriority(NotificationCompat.PriorityMax);
                            notificationBuilder.SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
                            break;

                        case "high":
                            notificationBuilder.SetPriority(NotificationCompat.PriorityHigh);
                            notificationBuilder.SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
                            break;

                        case "default":
                            notificationBuilder.SetPriority(NotificationCompat.PriorityDefault);
                            notificationBuilder.SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
                            break;

                        case "low":
                            notificationBuilder.SetPriority(NotificationCompat.PriorityLow);
                            break;

                        case "min":
                            notificationBuilder.SetPriority(NotificationCompat.PriorityMin);
                            break;

                        default:
                            notificationBuilder.SetPriority(NotificationCompat.PriorityDefault);
                            notificationBuilder.SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
                            break;
                        }
                    }
                    else
                    {
                        notificationBuilder.SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
                    }
                }
                else
                {
                    notificationBuilder.SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
                }

                try
                {
                    notificationBuilder.SetSound(soundUri);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"{DomainTag} - Failed to set sound {ex}");
                }
            }

            // Try to resolve (and apply) localized parameters
            ResolveLocalizedParameters(notificationBuilder, parameters);

            if (notificationColor != null)
            {
                notificationBuilder.SetColor(notificationColor.Value);
            }

            if (Build.VERSION.SdkInt >= BuildVersionCodes.JellyBean)
            {
                // Using BigText notification style to support long message
                var style = new NotificationCompat.BigTextStyle();
                style.BigText(message);
                notificationBuilder.SetStyle(style);
            }

            var category = string.Empty;

            if (parameters.TryGetValue(CategoryKey, out var categoryContent))
            {
                category = categoryContent.ToString();
            }

            if (parameters.TryGetValue(ActionKey, out var actionContent))
            {
                category = actionContent.ToString();
            }

            var notificationCategories = CrossPushNotification.Current?.GetUserNotificationCategories();

            if (notificationCategories != null && notificationCategories.Length > 0)
            {
                foreach (var userCat in notificationCategories)
                {
                    if (userCat != null && userCat.Actions != null && userCat.Actions.Count > 0)
                    {
                        foreach (var action in userCat.Actions)
                        {
                            var aRequestCode = Guid.NewGuid().GetHashCode();
                            if (userCat.Category.Equals(category, StringComparison.CurrentCultureIgnoreCase))
                            {
                                Intent                    actionIntent        = null;
                                PendingIntent             pendingActionIntent = null;
                                NotificationCompat.Action nAction             = null;
                                if (action.Type == NotificationActionType.Foreground)
                                {
                                    actionIntent = typeof(Activity).IsAssignableFrom(PushNotificationManager.NotificationActivityType) ? new Intent(Application.Context, PushNotificationManager.NotificationActivityType) : (PushNotificationManager.DefaultNotificationActivityType == null ? context.PackageManager.GetLaunchIntentForPackage(context.PackageName) : new Intent(Application.Context, PushNotificationManager.DefaultNotificationActivityType));

                                    if (PushNotificationManager.NotificationActivityFlags != null)
                                    {
                                        actionIntent.SetFlags(PushNotificationManager.NotificationActivityFlags.Value);
                                    }

                                    extras.PutString(ActionIdentifierKey, action.Id);
                                    actionIntent.PutExtras(extras);
                                    pendingActionIntent = PendingIntent.GetActivity(context, aRequestCode, actionIntent, PendingIntentFlags.UpdateCurrent);
                                    nAction             = new NotificationCompat.Action.Builder(context.Resources.GetIdentifier(action.Icon, "drawable", Application.Context.PackageName), action.Title, pendingActionIntent).Build();
                                }
                                else if (action.Type == NotificationActionType.Reply)
                                {
                                    var input = new RemoteInput.Builder("Result").SetLabel(action.Title).Build();

                                    actionIntent = new Intent(context, typeof(PushNotificationReplyReceiver));
                                    extras.PutString(ActionIdentifierKey, action.Id);
                                    actionIntent.PutExtras(extras);

                                    pendingActionIntent = PendingIntent.GetBroadcast(context, aRequestCode, actionIntent, PendingIntentFlags.UpdateCurrent);

                                    nAction = new NotificationCompat.Action.Builder(context.Resources.GetIdentifier(action.Icon, "drawable", Application.Context.PackageName), action.Title, pendingActionIntent)
                                              .SetAllowGeneratedReplies(true)
                                              .AddRemoteInput(input)
                                              .Build();
                                }
                                else
                                {
                                    actionIntent = new Intent(context, typeof(PushNotificationActionReceiver));
                                    extras.PutString(ActionIdentifierKey, action.Id);
                                    actionIntent.PutExtras(extras);
                                    pendingActionIntent = PendingIntent.GetBroadcast(context, aRequestCode, actionIntent, PendingIntentFlags.UpdateCurrent);
                                    nAction             = new NotificationCompat.Action.Builder(context.Resources.GetIdentifier(action.Icon, "drawable", Application.Context.PackageName), action.Title, pendingActionIntent).Build();
                                }

                                notificationBuilder.AddAction(nAction);
                            }
                        }
                    }
                }
            }

            OnBuildNotification(notificationBuilder, parameters);

            var notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService);

            notificationManager.Notify(tag, notifyId, notificationBuilder.Build());
        }
Exemplo n.º 21
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            var intent        = new Intent(this, typeof(MainActivity));
            var contentIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.CancelCurrent);
            var manager       = NotificationManagerCompat.From(this);



            var title       = "I <3 C#";
            var message     = "Seattle Code Camp rocks!";
            var messageLong = "Seattle Code Camp is awesome, I can't wait to see the Xamarin.Forms Demo later! From what I hear it is going to be the best thing ever!";



            //Standard Notification
            FindViewById <Button>(Resource.Id.notification).Click += (sender, e) => {
                var style = new NotificationCompat.BigTextStyle();
                style.BigText(messageLong);

                //Generate a notification with just short text and small icon
                var builder = new NotificationCompat.Builder(this)
                              .SetContentIntent(contentIntent)
                              .SetSmallIcon(Resource.Drawable.ic_stat_hexagon_blue)
                              .SetContentTitle(title)
                              .SetContentText(message)
                              .SetStyle(style)
                              .SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis())
                              .SetAutoCancel(true);


                var notification = builder.Build();
                manager.Notify(0, notification);
            };

            //Standard action with action
            FindViewById <Button>(Resource.Id.notification_action).Click += (sender, e) => {
                NotificationCompat.Action reply =
                    new NotificationCompat.Action.Builder(Resource.Drawable.ic_stat_social_reply,
                                                          "Reply", contentIntent)
                    .Build();

                var style = new NotificationCompat.BigTextStyle();
                style.BigText(messageLong);

                //Generate a notification with just short text and small icon
                var builder = new NotificationCompat.Builder(this)
                              .SetContentIntent(contentIntent)
                              .SetSmallIcon(Resource.Drawable.ic_stat_hexagon_blue)
                              .SetContentTitle(title)
                              .SetContentText(message)
                              .SetStyle(style)
                              .SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis())
                              .SetAutoCancel(true)
                              .AddAction(reply);


                var notification = builder.Build();
                manager.Notify(0, notification);
            };


            //Special Button for Wear
            FindViewById <Button>(Resource.Id.notification_wear_action).Click += (sender, e) => {
                NotificationCompat.Action favorite =
                    new NotificationCompat.Action.Builder(Resource.Drawable.ic_stat_rating_favorite,
                                                          "Favorite", contentIntent)
                    .Build();

                NotificationCompat.Action reply =
                    new NotificationCompat.Action.Builder(Resource.Drawable.ic_stat_social_reply,
                                                          "Reply", contentIntent)
                    .Build();


                var style = new NotificationCompat.BigTextStyle();
                style.BigText(messageLong);

                //Generate a notification with just short text and small icon
                var builder = new NotificationCompat.Builder(this)
                              .SetContentIntent(contentIntent)
                              .SetSmallIcon(Resource.Drawable.ic_stat_hexagon_blue)
                              .SetContentTitle(title)
                              .SetContentText(message)
                              .SetStyle(style)
                              .SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis())
                              .SetAutoCancel(true)
                              .AddAction(reply)
                              .Extend(new NotificationCompat.WearableExtender().AddActions(new [] { reply, favorite }));


                var notification = builder.Build();
                manager.Notify(0, notification);
            };

            //Custom Background
            FindViewById <Button>(Resource.Id.notification_wear_background).Click += (sender, e) => {
                var action = new NotificationCompat.Action.Builder(Resource.Drawable.ic_stat_rating_favorite,
                                                                   "Favorite", contentIntent)
                             .Build();

                var wearableExtender = new NotificationCompat.WearableExtender()
                                       .SetHintHideIcon(true)
                                       .SetBackground(BitmapFactory.DecodeResource(Resources, Resource.Drawable.ic_background))
                                       .AddAction(action)
                ;

                var style = new NotificationCompat.BigTextStyle();
                style.BigText(messageLong);

                //Generate a notification with just short text and small icon
                var builder = new NotificationCompat.Builder(this)
                              .SetContentIntent(contentIntent)
                              .SetSmallIcon(Resource.Drawable.ic_stat_hexagon_blue)
                              .SetContentTitle(title)
                              .SetContentText(message)
                              .SetStyle(style)
                              .SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis())
                              .SetAutoCancel(true)
                              .AddAction(Resource.Drawable.ic_stat_social_reply,
                                         "Reply", contentIntent)
                              .Extend(wearableExtender);


                var notification = builder.Build();
                manager.Notify(0, notification);
            };

            //Pages
            FindViewById <Button>(Resource.Id.notification_wear_pages).Click += (sender, e) => {
                // Create builder for the main notification
                var notificationBuilder =
                    new NotificationCompat.Builder(this)
                    .SetSmallIcon(Resource.Drawable.ic_stat_hexagon_blue)
                    .SetContentTitle("Page 1")
                    .SetContentText("Short message")
                    .SetContentIntent(contentIntent);

                // Create a big text style for the second page
                var secondPageStyle = new NotificationCompat.BigTextStyle();
                secondPageStyle.SetBigContentTitle("Page 2")
                .BigText(messageLong);

                // Create second page notification
                var secondPageNotification = new NotificationCompat.Builder(this)
                                             .SetStyle(secondPageStyle)
                                             .Build();

                // Add second page with wearable extender and extend the main notification
                var twoPageNotification =
                    new NotificationCompat.WearableExtender()
                    .AddPage(secondPageNotification)
                    .Extend(notificationBuilder)
                    .Build();

                // Issue the notification
                manager.Notify(0, twoPageNotification);
            };

            //Stacked Notifications
            FindViewById <Button>(Resource.Id.notification_wear_stacked).Click += (sender, e) => {
                var wearableExtender =
                    new NotificationCompat.WearableExtender()
                    .SetBackground(BitmapFactory.DecodeResource(Resources, Resource.Drawable.ic_background));

                // Build the notification, setting the group appropriately
                var notificaiton1 = new NotificationCompat.Builder(this)
                                    .SetContentTitle("New mail from James")
                                    .SetContentText(message)
                                    .SetSmallIcon(Resource.Drawable.ic_stat_hexagon_blue)
                                    .SetGroup("group_1")
                                    .Extend(wearableExtender)
                                    .Build();


                var notification2 = new NotificationCompat.Builder(this)
                                    .SetContentTitle("New mail from ChrisNTR")
                                    .SetContentText("this is subject #1")
                                    .SetSmallIcon(Resource.Drawable.ic_stat_hexagon_blue)
                                    .SetGroup("group_1")
                                    .Extend(wearableExtender)
                                    .Build();

                manager.Notify(0, notificaiton1);
                manager.Notify(1, notification2);
            };

            //Voice Input
            FindViewById <Button>(Resource.Id.notification_wear_voice).Click += (sender, e) => {
                var remoteInput = new Android.Support.V4.App.RemoteInput.Builder(ExtraVoiceReply)
                                  .SetLabel("Reply")
                                  .SetChoices(new [] { "Yes", "No", "OK you win" })
                                  .Build();

                NotificationCompat.Action reply =
                    new NotificationCompat.Action.Builder(Resource.Drawable.ic_stat_social_reply,
                                                          "Reply", contentIntent)
                    .AddRemoteInput(remoteInput)

                    .Build();


                var wearableExtender = new NotificationCompat.WearableExtender();
                wearableExtender.AddAction(reply);


                //Generate a notification with just short text and small icon
                var builder = new NotificationCompat.Builder(this)
                              .SetContentIntent(contentIntent)
                              .SetSmallIcon(Resource.Drawable.ic_stat_hexagon_blue)
                              .SetContentTitle(title)
                              .SetContentText(message)
                              .SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis())
                              .SetAutoCancel(true)
                              .AddAction(reply)
                              .Extend(wearableExtender);


                var notification = builder.Build();
                manager.Notify(0, notification);
            };

            var voiceReply = GetMessageText(Intent);

            if (!string.IsNullOrWhiteSpace(voiceReply))
            {
                FindViewById <TextView> (Resource.Id.textView1).Text = voiceReply;
            }
        }
Exemplo n.º 22
0
        public void PresentNotification(string title, string text, bool endCounter)
        {
            this.builder.SetVisibility((int)NotificationVisibility.Public);
            this.builder.SetContentTitle(title);
            this.builder.SetContentText(text);
            this.builder.SetSmallIcon(Resource.Drawable.IconSmall);
            this.builder.SetCategory(Notification.CategoryEvent);
            this.builder.SetOngoing(true);
            this.builder.SetAutoCancel(false);
            this.builder.SetShowWhen(false);

            if (endCounter)
            {
                this.builder.SetPriority((int)NotificationPriority.High);
                this.builder.SetDefaults((int)NotificationDefaults.All);
            }
            else
            {
                this.builder.SetPriority((int)NotificationPriority.Min);
                this.builder.SetDefaults((int)NotificationDefaults.Vibrate);
            }

            if (title.Contains("Ready"))
            {
                this.builder.MActions.Clear();

                Intent        shiftIntent  = new Intent(KEY_TOGGLE_SHIFT);
                PendingIntent shiftPending = PendingIntent.GetBroadcast(Forms.Context, 0, shiftIntent, PendingIntentFlags.UpdateCurrent);

                NotificationCompat.Action action = new NotificationCompat.Action.Builder(Resource.Drawable.icon, "Start Shift", shiftPending).Build();

                this.builder.AddAction(action);
            }
            else if (title.Contains("Shift"))
            {
                this.builder.MActions.Clear();

                Intent        shiftIntent  = new Intent(KEY_TOGGLE_SHIFT);
                PendingIntent shiftPending = PendingIntent.GetBroadcast(Forms.Context, 0, shiftIntent, PendingIntentFlags.UpdateCurrent);

                Intent        driveIntent  = new Intent(KEY_TOGGLE_DRIVE);
                PendingIntent drivePending = PendingIntent.GetBroadcast(Forms.Context, 0, driveIntent, PendingIntentFlags.UpdateCurrent);

                Intent        breakIntent  = new Intent(KEY_TOGGLE_BREAK);
                PendingIntent breakPending = PendingIntent.GetBroadcast(Forms.Context, 1, breakIntent, PendingIntentFlags.UpdateCurrent);

                NotificationCompat.Action action = new NotificationCompat.Action.Builder(Resource.Drawable.icon, "End Shift", shiftPending).Build();

                NotificationCompat.Action actionDrive = new NotificationCompat.Action.Builder(Resource.Drawable.icon, "Start Drive", drivePending).Build();

                NotificationCompat.Action actionBreak = new NotificationCompat.Action.Builder(Resource.Drawable.icon, "Start Break", breakPending).Build();

                this.builder.AddAction(action);
                this.builder.AddAction(actionDrive);
                this.builder.AddAction(actionBreak);
            }
            else if (title.Contains("Drive"))
            {
                this.builder.MActions.Clear();

                Intent        driveIntent  = new Intent(KEY_TOGGLE_DRIVE);
                PendingIntent drivePending = PendingIntent.GetBroadcast(Forms.Context, 0, driveIntent, PendingIntentFlags.UpdateCurrent);

                Intent        breakIntent  = new Intent(KEY_TOGGLE_BREAK);
                PendingIntent breakPending = PendingIntent.GetBroadcast(Forms.Context, 1, breakIntent, PendingIntentFlags.UpdateCurrent);

                NotificationCompat.Action action = new NotificationCompat.Action.Builder(Resource.Drawable.icon, "End Drive", drivePending).Build();

                NotificationCompat.Action actionBreak = new NotificationCompat.Action.Builder(Resource.Drawable.icon, "Start Break", breakPending).Build();

                this.builder.AddAction(action);
                this.builder.AddAction(actionBreak);
            }
            else if (title.Contains("Break"))
            {
                this.builder.MActions.Clear();

                Intent        intent  = new Intent(KEY_TOGGLE_BREAK);
                PendingIntent pending = PendingIntent.GetBroadcast(Forms.Context, 0, intent, PendingIntentFlags.UpdateCurrent);

                NotificationCompat.Action action = new NotificationCompat.Action.Builder(Resource.Drawable.icon, "End Break", pending).Build();

                this.builder.AddAction(action);
            }

            Notification notification = this.builder.Build();

            this.notifyManager.Notify(Id, notification);
        }
Exemplo n.º 23
0
        private async void ShowNotification(Intent intent)
        {
            const string msgKey      = "msg";
            const string senderIdKey = "senderid";
            const string senderKey   = "sender";
            const string iconKey     = "icon";

            if (!intent.Extras.ContainsKey(msgKey) || !intent.Extras.ContainsKey(senderIdKey) ||
                !intent.Extras.ContainsKey(senderKey) || !intent.Extras.ContainsKey(iconKey))
            {
                return;
            }

            NotificationMessage notification = new NotificationMessage();

            notification.Title   = intent.Extras.GetString(senderKey);
            notification.Message = intent.Extras.GetString(msgKey);
            notification.IconUrl = intent.Extras.GetString(iconKey);
            notification.FromId  = int.Parse(intent.Extras.GetString(senderIdKey));

            Bitmap largeIconBitmap = await GetImageBitmapFromUrlAsync(EndPoints.BaseUrl + notification.IconUrl);

            var notificationManager = NotificationManagerCompat.From(this);

            Intent notificationIntent = null;

            int id = notification.FromId;

            //if user id came in then let's send them to that page.
            if (id <= 0)
            {
                id = Settings.GetNotificationId();
                notificationIntent = new Intent(this, typeof(WelcomeActivity));
            }
            else
            {
                notificationIntent = new Intent(this, typeof(ConversationActivity));
                notificationIntent.PutExtra(ConversationActivity.RecipientId, (long)id);
            }

            notificationIntent.AddFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask);
            var pendingIntent = PendingIntent.GetActivity(this, 0, notificationIntent, PendingIntentFlags.UpdateCurrent);

            var wearableExtender =
                new NotificationCompat.WearableExtender()
                .SetContentIcon(Resource.Drawable.ic_launcher);

            NotificationCompat.Action reply =
                new NotificationCompat.Action.Builder(Resource.Drawable.ic_stat_social_reply,
                                                      "Reply", pendingIntent)
                .Build();

            var builder = new NotificationCompat.Builder(this)
                          .SetContentIntent(pendingIntent)
                          .SetContentTitle(notification.Title)
                          .SetAutoCancel(true)
                          .SetSmallIcon(Resource.Drawable.ic_notification)
                          .SetLargeIcon(largeIconBitmap)
                          .SetContentText(notification.Message)
                          .AddAction(reply)
                          .Extend(wearableExtender);

            // Obtain a reference to the NotificationManager

            var notif = builder.Build();

            notif.Defaults = NotificationDefaults.All;             //add sound, vibration, led :)

            notificationManager.Notify(id, notif);
        }