/// <summary> /// /// </summary> /// <param name="request"></param> /// <param name="serializedRequest"></param> /// <param name="action"></param> /// <returns></returns> protected virtual NotificationCompat.Action CreateAction(NotificationRequest request, string serializedRequest, NotificationAction action) { var pendingIntent = CreateActionIntent(serializedRequest, action); var nativeAction = new NotificationCompat.Action(GetIcon(request.Android.IconSmallName), new Java.Lang.String(action.Title), pendingIntent); return(nativeAction); }
public Notification CreateNotification() { var contentIntent = PendingIntent.GetActivity(this, 0, new Intent(this, typeof(SwipeTabActivity)), PendingIntentFlags.UpdateCurrent); var builder = new NotificationCompat.Builder(this) .SetContentTitle("4Fitness on the go") .SetSmallIcon(Resource.Drawable.icon_notification) .SetPriority(1) .SetContentIntent(contentIntent) .SetCategory("tst") .SetStyle(new NotificationCompat.BigTextStyle() .BigText(Html.FromHtml("Tap to Open"))) .SetContentText(Html.FromHtml("Tap to Open")); var clossIntent = new Intent(this, typeof(CloseApplicationActivity)); clossIntent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask | ActivityFlags.ClearTop); var dismissIntent = PendingIntent.GetActivity(this, 0, clossIntent, PendingIntentFlags.CancelCurrent); var action = new NotificationCompat.Action(Resource.Drawable.switch_off, "Switch off", dismissIntent); builder.AddAction(action); var n = builder.Build(); n.Flags |= NotificationFlags.NoClear; return(n); }
private async Task StartProgress(int secs = 10) { var notificationId = 65324; var manager = (NotificationManager)GetSystemService(NotificationService); alertCancellation = new CancellationTokenSource(); int i = 0; while (i <= secs && !alertCancellation.Token.IsCancellationRequested) { var intent = new Intent(this, typeof(SecurityService)); intent.SetAction("CANCEL_ALERT"); var pendingIntent = PendingIntent.GetService(this, 0, intent, PendingIntentFlags.OneShot); var cancelAction = new NotificationCompat.Action(0, "Cancelar", pendingIntent); var notification = new NotificationCompat.Builder(this, ChannelId) .SetSmallIcon(Resource.Drawable.shield1) .AddAction(cancelAction) .SetContentTitle("Enviando alerta") .SetContentText("Te encuentras bien? Vamos a enviar una alerta.") .SetProgress(secs, i, false) .SetOngoing(true) .Build(); manager.Notify(notificationId, notification); i++; await Task.Delay(TimeSpan.FromSeconds(1)); } if (!alertCancellation.Token.IsCancellationRequested) { // Enviar alerta Toast.MakeText(this, "Alerta enviada!", ToastLength.Long).Show(); } else { Toast.MakeText(this, "Alerta CANCELADA!", ToastLength.Long).Show(); } manager.Cancel(notificationId); }
/// <summary> /// Initialise the bits and bobs used for the notification /// </summary> private void InitialiseNotification() { // The mediaButtonReceiver parameter is required for pre-Lollipop SDK ComponentName mediaButtonReceiver = new(this, Java.Lang.Class.FromType(typeof(MediaButtonReceiver))); MediaSessionCompat mediaSession = new(this, AudioPlayerId, mediaButtonReceiver, null) { Active = true }; mediaStyle = new MediaStyle().SetMediaSession(mediaSession.SessionToken).SetShowActionsInCompactView(0); // The play and pause actions to be triggered when the icon is clicked playAction = new NotificationCompat.Action(Android.Resource.Drawable.IcMediaPlay, "play", PlaybackAction(PlayActionName)); pauseAction = new NotificationCompat.Action(Android.Resource.Drawable.IcMediaPause, "pause", PlaybackAction(PauseActionName)); if (Build.VERSION.SdkInt >= BuildVersionCodes.O) { NotificationChannel channel = new(AudioPlayerId, ChannelName, NotificationImportance.Low) { Description = ChannelDescription }; NotificationManager.FromContext(this).CreateNotificationChannel(channel); } }
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()); }
public void Send(NotificationType notificationType, string text) { var categoryTitle = "DummyCategoryTitle"; var title = "DummyTitle"; var description = "BaseDescription"; var builder = new NotificationCompat.Builder(mContext, title); builder.SetPriority(NotificationCompat.PriorityHigh); var importance = NotificationImportance.Max; switch (notificationType) { case NotificationType.WarningNotification: categoryTitle = DataHolder.CategoriesDictionary[mCategory].Title; title = string.Format(mContext.GetString(Resource.String.notification_type_warning), categoryTitle); description = string.Format(mContext.GetString(Resource.String.notification_type_warning_description), categoryTitle); break; case NotificationType.SummaryNotification: title = "Summary"; description = "This channel is used to send summaries"; break; case NotificationType.InfoNotification: title = categoryTitle + " Info"; description = $"This channel is used to send information associated with {categoryTitle}"; builder.SetPriority(NotificationCompat.PriorityDefault); importance = NotificationImportance.Default; break; } builder.SetContentTitle(title) .SetContentText(text) .SetChannelId(mCategory) .SetDefaults(NotificationCompat.DefaultSound) .SetAutoCancel(true); Intent intent; switch (notificationType) { case NotificationType.WarningNotification: intent = new Intent(mContext, typeof(CategoryInfoActivity)); intent.PutExtra(ExtraNotificationId, mCategory.GetHashCode()); intent.PutExtra(ExtraNotificationCategory, mCategory); var pendingIntent = PendingIntent.GetActivity(mContext, (int)notificationType, intent, PendingIntentFlags.CancelCurrent); var makeNormal = new NotificationCompat.Action(Resource.Drawable.ic_notif_normalize, mContext.GetString(Resource.String.notification_button_normalize), IntentToNormalize(CreateNormalizeIntent())); var viewDetails = new NotificationCompat.Action(Resource.Drawable.ic_notif_details, mContext.GetString(Resource.String.notification_button_details), pendingIntent); builder .SetSmallIcon(Android.Resource.Drawable.StatSysWarning) .SetContentIntent(pendingIntent) .AddAction(makeNormal) .AddAction(viewDetails); break; case NotificationType.InfoNotification: builder.SetSmallIcon(Resource.Drawable.ic_stat_info); break; case NotificationType.SummaryNotification: intent = new Intent(mContext, typeof(CategoryInfoActivity)); intent.PutExtra(ExtraNotificationId, mCategory.GetHashCode()); intent.PutExtra(ExtraNotificationCategory, mCategory); intent.PutExtra(AlarmReceiver.ExtraSummaryText, text); var exportSummary = new NotificationCompat.Action(Resource.Drawable.ic_notif_export, mContext.GetString(Resource.String.notification_button_export), IntentToNormalize(CreateNormalizeIntent())); builder .SetSmallIcon(Resource.Drawable.ic_stat_summary) .AddAction(exportSummary); break; default: builder.SetSmallIcon(Resource.Mipmap.Icon); break; } if (Build.VERSION.SdkInt >= BuildVersionCodes.O) { var channel = new NotificationChannel(mCategory, title, importance) { Description = description, LightColor = Color.Red }; channel.EnableLights(true); channel.EnableVibration(true); notificationManager.CreateNotificationChannel(channel); } var bigNotification = new NotificationCompat.BigTextStyle(builder) .BigText(text).Build(); notificationManager.Notify(mCategory.GetHashCode(), bigNotification); }