Exemplo n.º 1
0
        public virtual void ApplyChannel(NotificationCompat.Builder builder, Notification notification, Channel channel)
        {
            if (channel == null)
            {
                return;
            }

            builder.SetChannelId(channel.Identifier);
            if (channel.Actions != null)
            {
                foreach (var action in channel.Actions)
                {
                    switch (action.ActionType)
                    {
                    case ChannelActionType.OpenApp:
                        break;

                    case ChannelActionType.TextReply:
                        var textReplyAction = this.CreateTextReply(notification, action);
                        builder.AddAction(textReplyAction);
                        break;

                    case ChannelActionType.None:
                    case ChannelActionType.Destructive:
                        var destAction = this.CreateAction(notification, action);
                        builder.AddAction(destAction);
                        break;

                    default:
                        throw new ArgumentException("Invalid action type");
                    }
                }
            }
        }
 private void AddPlayPauseActionCompat(NotificationCompat.Builder builder)
 {
     if (MediaPlayerState == PlaybackStateCompat.StatePlaying)
     {
         builder.AddAction(GenerateActionCompat(Android.Resource.Drawable.IcMediaPause, "Pause", ActionPause));
     }
     else
     {
         builder.AddAction(GenerateActionCompat(Android.Resource.Drawable.IcMediaPlay, "Play", ActionPlay));
     }
 }
Exemplo n.º 3
0
        private async void StartNotification()
        {
            if (_mediaSessionCompat != null)
            {
                Intent        intent        = new Intent(ApplicationContext, typeof(MainActivity));
                PendingIntent pendingIntent = PendingIntent.GetActivity(ApplicationContext, 0, intent, PendingIntentFlags.UpdateCurrent);
                Track         currentSong   = _queue[_pos];

                Intent audioServiceIntent = new Intent(ApplicationContext, typeof(AudioService));
                audioServiceIntent.SetAction(ActionStop);
                PendingIntent pendingCancelIntent = PendingIntent.GetService(ApplicationContext, 1, audioServiceIntent, PendingIntentFlags.CancelCurrent);

                NotificationCompat.Builder builder = new NotificationCompat.Builder(ApplicationContext)
                                                     .SetContentTitle(currentSong.Title)
                                                     .SetContentText(currentSong.Artist)
                                                     .SetContentInfo(currentSong.Album)
                                                     .SetSmallIcon(Resource.Drawable.playlist_icon)
                                                     .SetContentIntent(pendingIntent)
                                                     .SetShowWhen(false)
                                                     .SetOngoing(true)
                                                     .SetVisibility(NotificationCompat.VisibilityPublic)
                                                     .SetDefaults(NotificationCompat.FlagNoClear)
                                                     .SetPriority(NotificationCompat.PriorityMax);

                Bitmap artwork;
                if (!String.IsNullOrEmpty(currentSong.Image.ToString()))
                {
                    artwork = await BitmapFactory.DecodeFileAsync(currentSong.Image.ToString());
                }
                else
                {
                    artwork = await BitmapFactory.DecodeResourceAsync(ApplicationContext.Resources, Resource.Drawable.playlist_icon);
                }
                builder.SetLargeIcon(artwork);

                builder.AddAction(GenerateActionCompat(Android.Resource.Drawable.IcMediaPrevious, "Prev", ActionPrev));
                AddPlayPauseActionCompat(builder);
                builder.AddAction(GenerateActionCompat(Android.Resource.Drawable.IcMediaNext, "Next", ActionNext));

                MediaStyle style = new MediaStyle();
                style.SetShowCancelButton(true);
                style.SetCancelButtonIntent(pendingCancelIntent);
                style.SetMediaSession(_mediaSessionCompat.SessionToken);
                style.SetShowActionsInCompactView(0, 1, 2);
                builder.SetStyle(style);

                StartForeground(1, builder.Build());
            }
        }
        private Notification GetUnlockedNotification()
        {
            NotificationCompat.Builder builder =
                new NotificationCompat.Builder(this)
                .SetOngoing(true)
                .SetSmallIcon(Resource.Drawable.ic_notify)
                .SetLargeIcon(MakeLargeIcon(BitmapFactory.DecodeResource(Resources, AppNames.NotificationUnlockedIcon)))
                .SetVisibility((int)Android.App.NotificationVisibility.Public)
                .SetContentTitle(GetString(Resource.String.app_name))
                .SetContentText(GetString(Resource.String.database_loaded_unlocked, GetDatabaseName()));

            if ((int)Build.VERSION.SdkInt >= 16)
            {
                if (PreferenceManager.GetDefaultSharedPreferences(this)
                    .GetBoolean(GetString(Resource.String.ShowUnlockedNotification_key),
                                Resources.GetBoolean(Resource.Boolean.ShowUnlockedNotification_default)))
                {
                    builder.SetPriority((int)NotificationPriority.Default);
                }
                else
                {
                    builder.SetPriority((int)NotificationPriority.Min);
                }
            }

            // Default action is to show Kp2A
            builder.SetContentIntent(GetSwitchToAppPendingIntent());
            // Additional action to allow locking the database
            builder.AddAction(Resource.Drawable.ic_action_lock, GetString(Resource.String.menu_lock), PendingIntent.GetBroadcast(this, 0, new Intent(Intents.LockDatabase), PendingIntentFlags.UpdateCurrent));

            return(builder.Build());
        }
Exemplo n.º 5
0
        public bool notificarPermanente(int id, string titulo, string descricao, int idParar, string textoParar, string acaoParar)
        {
            Context context = Android.App.Application.Context;

            Intent intent          = new Intent(context, pegarJanelaTipo());
            var    intentPrincipal = PendingIntent.GetActivity(context, 0, intent, PendingIntentFlags.OneShot);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
            builder.SetPriority((int)NotificationPriority.Max);
            builder.SetAutoCancel(true);
            builder.SetContentIntent(intentPrincipal);
            builder.SetNumber(id);
            builder.SetSmallIcon(pegarIconePequeno());
            builder.SetContentTitle(titulo);
            if (!string.IsNullOrEmpty(descricao))
            {
                builder.SetContentText(descricao);
            }
            //builder.SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Alarm));

            var acao = new Intent(context, pegarBroadcast());

            acao.SetAction(acaoParar);
            var pendingIntent = PendingIntent.GetBroadcast(context, idParar, acao, PendingIntentFlags.UpdateCurrent);

            builder.AddAction(new Android.Support.V4.App.NotificationCompat.Action(pegarIconeParar(), textoParar, pendingIntent));

            NotificationManager notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService);
            Notification        notificacao         = builder.Build();

            notificacao.Flags = NotificationFlags.NoClear;
            notificationManager.Notify(id, notificacao);

            return(true);
        }
Exemplo n.º 6
0
        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);
        }
Exemplo n.º 7
0
 private void AddActionButtons(bool mediaIsPlaying)
 {
     builder.MActions.Clear();
     builder.AddAction(mediaIsPlaying
         ? GenerateActionCompat(Resource.Drawable.pausearrow, "Pause", Thread_radio.ActionPause)
         : GenerateActionCompat(Resource.Drawable.playarrow, "Play", Thread_radio.ActionPlay));
 }
Exemplo n.º 8
0
        private void AddAction(NotificationCompat.Builder notificationBuilder, string title, string url)
        {
            var notificationIntent = new Intent(Intent.ActionView);

            notificationIntent.SetData(Android.Net.Uri.Parse(url));
            var buttonIntent = PendingIntent.GetActivity(Application.Context, 0, notificationIntent, 0);

            notificationBuilder.AddAction(0, title, buttonIntent);
        }
Exemplo n.º 9
0
        private void AddActionButtons(bool mediaIsPlaying)
        {
            _builder.MActions.Clear();

            Console.WriteLine("Adding action button: " + mediaIsPlaying.ToString());

            _builder.AddAction(mediaIsPlaying
                               ? GenerateActionCompat(Android.Resource.Drawable.IcMediaPause, "Pause", MediaServiceBase.ActionPause)
                               : GenerateActionCompat(Android.Resource.Drawable.IcMediaPlay, "Play", MediaServiceBase.ActionPlay));
        }
Exemplo n.º 10
0
        private Notification CreateNativeNotification(Context context, Models.Notification notification)
        {
            var builder = new NotificationCompat.Builder(Application.Context, AndroidAppEnvironment.CHANNEL_ID)
                          .SetAutoCancel(true)
                          .SetVisibility((int)NotificationVisibility.Public)
                          .SetContentIntent(PendingIntent.GetActivity(context, 0, new Intent(context, typeof(SplashActivity)),
                                                                      PendingIntentFlags.UpdateCurrent |
                                                                      PendingIntentFlags.Mutable))
                          .SetContentTitle(notification.Title)
                          .SetContentText(notification.Text)
                          .SetSmallIcon(Application.Context.ApplicationInfo.Icon);

            if (context.PackageManager.GetLaunchIntentForPackage("com.miHoYo.GenshinImpact") is not null)
            {
                Intent runIntent = new Intent(context, typeof(NotiActionReceiver))
                                   .SetAction("RUN_GENSHIN")
                                   .PutExtra("NotiId", notification.Id);

                PendingIntent pRunIntent = PendingIntent.GetBroadcast(context, 0, runIntent,
                                                                      PendingIntentFlags.UpdateCurrent |
                                                                      PendingIntentFlags.Mutable);

                builder.AddAction(0, AppResources.Noti_QuickAction_RunGenshinApp, pRunIntent);
            }

            if (!((notification.NotiType is NotiManager.NotificationType.Resin) ||
                  (notification.NotiType is NotiManager.NotificationType.RealmCurrency) ||
                  (notification.NotiType is NotiManager.NotificationType.RealmFriendship)))
            {
                Intent resetIntent = new Intent(context, typeof(NotiActionReceiver))
                                     .SetAction("RESET_TIMER")
                                     .PutExtra("NotiId", notification.Id)
                                     .PutExtra("NotiType", (int)notification.NotiType);

                PendingIntent pResetIntent = PendingIntent.GetBroadcast(context, 0, resetIntent,
                                                                        PendingIntentFlags.UpdateCurrent |
                                                                        PendingIntentFlags.Mutable);

                builder.AddAction(0, AppResources.Noti_QuickAction_ResetTimer, pResetIntent);
            }

            return(builder.Build());
        }
 void RegisterForegroundService()
 {
     NotificationCompat.Builder builder = GetNotificationBuilder("SensorApp.notification.CHANNEL_ID_FOREGROUND");
     builder.SetContentTitle(Resources.GetString(Resource.String.app_name));
     builder.SetContentText(Resources.GetString(Resource.String.notification_text));
     builder.SetSmallIcon(Resource.Drawable.ic_run);
     builder.SetContentIntent(BuildIntentToShowTrackingActivity());
     builder.SetOngoing(true);
     builder.AddAction(BuildStopServiceAction());
     StartForeground(Constants.SERVICE_RUNNING_NOTIFICATION_ID, builder.Build());
 }
Exemplo n.º 12
0
        /// <summary>
        /// Adds clickable button onto the notification
        /// </summary>
        /// <param name="id">The ID of button to add, used for identification purposes as well as ordering</param>
        /// <param name="title">The title to display on button</param>
        /// <param name="action">The name of the action to perform when button is clicked</param>
        /// <param name="taskService">The instance of task service which is running in the background</param>
        public void AddButton(int id, string title, string action, TaskService taskService)
        {
            // Prepare new intent for task service instance
            var intent = new Intent(Application.Context, typeof(TaskService));

            intent.SetAction(action).AddFlags(ActivityFlags.FromBackground);
            var pendingIntent = PendingIntent.GetService(taskService, id, intent, PendingIntentFlags.UpdateCurrent);

            // Add button action to the notification
            mNotificationBuilder.AddAction(Resource.Drawable.logo, title, pendingIntent);
        }
Exemplo n.º 13
0
        //https://segunfamisa.com/posts/notifications-direct-reply-android-nougat
        protected virtual void AddCategory(NotificationCompat.Builder builder, Notification notification)
        {
            if (notification.Category.IsEmpty() || !this.context.IsMinApiLevel(24))
            {
                return;
            }

            var category = this.registeredCategories.FirstOrDefault(x => x.Identifier.Equals(notification.Category));

            if (category == null)
            {
                Log.Write(NotificationLogCategory.Notifications, "No notification category found for " + notification.Category);
            }
            else
            {
                var notificationString = this.serializer.Serialize(notification);

                foreach (var action in category.Actions)
                {
                    switch (action.ActionType)
                    {
                    case NotificationActionType.OpenApp:
                        break;

                    case NotificationActionType.TextReply:
                        var textReplyAction = this.CreateTextReply(notification, action);
                        builder.AddAction(textReplyAction);
                        break;

                    case NotificationActionType.None:
                    case NotificationActionType.Destructive:
                        var destAction = this.CreateAction(notification, action);
                        builder.AddAction(destAction);
                        break;

                    default:
                        throw new ArgumentException("Invalid action type");
                    }
                }
            }
        }
Exemplo n.º 14
0
        public override void OnReceive(Context context, Intent intent)
        {
            var bigStyle = new NotificationCompat.BigTextStyle().BigText("Telah Terjadi Tsunami");
            // Create a PendingIntent; we're only using one PendingIntent (ID = 0):
            NotificationManager notificationManager = context.GetSystemService(Context.NotificationService) as NotificationManager;

            NotificationCompat.Builder builder = new NotificationCompat.Builder(context, MainActivity.CHANNEL_ID)
                                                 //  .SetContentIntent(pendingIntent)
                                                 .SetContentTitle("Sirine Tsunami")
                                                 .SetContentText("Sirine Tsunami")
                                                 .SetAutoCancel(true)
                                                 .SetStyle(bigStyle)
                                                 .SetSound(soundUri)
                                                 .SetPriority(NotificationCompat.PriorityMax)
                                                 .SetSmallIcon(Resource.Drawable.icontsunami);

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

            Intent        intents       = new Intent(Intent.ActionView, Android.Net.Uri.Parse("http://inatews.bmkg.go.id/terkini.php"));
            PendingIntent pendingIntent = PendingIntent.GetActivity(context, MainActivity.NOTIFICATION_ID, intents, PendingIntentFlags.UpdateCurrent);

            Intent buttonIntent = new Intent(context, typeof(DissmisService));

            buttonIntent.PutExtra("notificationId", MainActivity.CHANNEL_ID);
            PendingIntent dismissIntent = PendingIntent.GetBroadcast(context, MainActivity.NOTIFICATION_ID, buttonIntent, PendingIntentFlags.CancelCurrent);

            builder.AddAction(Resource.Drawable.abc_ic_menu_overflow_material, "VIEW", pendingIntent);
            builder.AddAction(Resource.Drawable.abc_ic_menu_cut_mtrl_alpha, "DISMISS", dismissIntent);

            NotifyBroadcastReceived.ringtone = NotifyBroadcastReceived.ringtone ?? RingtoneManager.GetRingtone(context, soundUri);

            if (!NotifyBroadcastReceived.ringtone.IsPlaying)
            {
                NotifyBroadcastReceived.ringtone.Play();
            }

            notificationManager.Notify(MainActivity.NOTIFICATION_ID, builder.Build());
        }
        private void AddActionButtons(bool mediaIsPlaying)
        {
            // Add previous/next button based on media queue
            var canGoPrevious = MediaQueue?.HasPrevious() ?? false;
            var canGoNext     = MediaQueue?.HasNext() ?? false;

            _builder.MActions.Clear();
            if (canGoPrevious)
            {
                _builder.AddAction(GenerateActionCompat(Resource.Drawable.IcMediaPrevious, "Previous",
                                                        MediaServiceBase.ActionPrevious));
            }
            _builder.AddAction(mediaIsPlaying
                ? GenerateActionCompat(Resource.Drawable.IcMediaPause, "Pause", MediaServiceBase.ActionPause)
                : GenerateActionCompat(Resource.Drawable.IcMediaPlay, "Play", MediaServiceBase.ActionPlay));
            if (canGoNext)
            {
                _builder.AddAction(GenerateActionCompat(Resource.Drawable.IcMediaNext, "Next",
                                                        MediaServiceBase.ActionNext));
            }
        }
        /// <summary>
        /// When we start on the foreground we will present a notification to the user
        /// When they press the notification it will take them to the main page so they can control the music
        /// </summary>
        private void StartNotification()
        {
            if (mediaSessionCompat == null)
            {
                return;
            }

            var pendingIntent = PendingIntent.GetActivity(ApplicationContext, 0, new Intent(ApplicationContext, typeof(MainActivity)), PendingIntentFlags.UpdateCurrent);
            MediaMetadataCompat currentTrack = mediaControllerCompat.Metadata;

            Android.Support.V7.App.NotificationCompat.MediaStyle style = new Android.Support.V7.App.NotificationCompat.MediaStyle();
            style.SetMediaSession(mediaSessionCompat.SessionToken);

            Intent intent = new Intent(ApplicationContext, typeof(MediaPlayerService));

            intent.SetAction(ActionStop);
            PendingIntent pendingCancelIntent = PendingIntent.GetService(ApplicationContext, 1, intent, PendingIntentFlags.CancelCurrent);

            style.SetShowCancelButton(true);
            style.SetCancelButtonIntent(pendingCancelIntent);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(ApplicationContext)
                                                 .SetStyle(style)
                                                 .SetContentTitle(currentTrack.GetString(MediaMetadata.MetadataKeyTitle))
                                                 .SetContentText(currentTrack.GetString(MediaMetadata.MetadataKeyArtist))
                                                 .SetContentInfo(currentTrack.GetString(MediaMetadata.MetadataKeyAlbum))
                                                 .SetSmallIcon(Resource.Drawable.album_art)
                                                 .SetLargeIcon(Cover as Bitmap)
                                                 .SetContentIntent(pendingIntent)
                                                 .SetShowWhen(false)
                                                 .SetOngoing(MediaPlayerState == PlaybackStateCompat.StatePlaying)
                                                 .SetVisibility(NotificationCompat.VisibilityPublic);

            builder.AddAction(GenerateActionCompat(Android.Resource.Drawable.IcMediaPrevious, "Previous", ActionPrevious));
            AddPlayPauseActionCompat(builder);
            builder.AddAction(GenerateActionCompat(Android.Resource.Drawable.IcMediaNext, "Next", ActionNext));
            style.SetShowActionsInCompactView(0, 1, 2);

            NotificationManagerCompat.From(ApplicationContext).Notify(NotificationId, builder.Build());
        }
        /// <summary>
        ///     Sends a local notification
        /// </summary>
        /// <param name="content">
        ///     The content of the notification
        /// </param>
        public void Notify(NotificationContent content)
        {
            // Get the current content
            var context = Android.App.Application.Context;

            // If the context cannot be found, don't do anything
            if (context == null)
            {
                return;
            }

            // Get the resource ID for the icon
            var iconId = context.Resources.GetIdentifier(content.IconSource, "drawable", context.PackageName);

            // Get the defaults
            var defaults = GenerateDefaults(content);

            // Generate extras
            var extras = GenerateExtras(content);

            // Create the intent
            var intent = CreateIntent(context, extras);

            // Build the notification
            var builder = new NotificationCompat.Builder(context, "mobile-examples")
                          .SetContentIntent(intent)
                          .SetContentTitle(content.Title)
                          .SetContentText(content.Body)
                          .SetSmallIcon(iconId)
                          .SetDefaults(defaults)
                          .AddExtras(extras)
                          .SetAutoCancel(true);

            var buttonIntent = new Intent("actionButton"); // Create an Intent to be used by this button

            // the button needs to use this as a Pending Intent.   the .GetBroadcast method is used as we want to receive this
            //pending intent though a broadcast receiver.   use a different method if you want to handle it in a different way
            var buttonPending = PendingIntent.GetBroadcast(context, 0, buttonIntent, PendingIntentFlags.UpdateCurrent);

            builder.AddAction(iconId, "action button", buttonPending); // Adds the button onto the notification

            var notification = builder.Build();

            // Get the notification manager
            var notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService);

            // Publish the notification
            notificationManager.Notify(content.Id, notification);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Creates a single notification, an instance of <see cref="Android.App.Notification"/> class.
        /// </summary>
        /// <returns>Android notification created from <b>notification</b> parameter.</returns>
        /// <param name="notification"><b>CoreNotification</b></param>
        private Notification GetNotification(CoreNotification notification, DateTime occurrence, Intent notificationIntent)
        {
            var builder = new NotificationCompat.Builder(this.ctx);

            builder.SetContentTitle(notification.Title);
            builder.SetContentText(notification.Message + this.FormatOccurrence(occurrence));
            builder.SetTicker("Ticker");
            builder.SetSmallIcon(Resource.Drawable.Icon);

            builder.SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Alarm));
            builder.SetPriority((int)NotificationPriority.High);
            builder.SetVisibility((int)NotificationVisibility.Public);  // visible on locked screen

            var action = this.GetAction(builder, notificationIntent, () => { System.Diagnostics.Debug.WriteLine("ACTION!"); });

            builder.AddAction(action);

            return(builder.Build());
        }
Exemplo n.º 19
0
        private void ShowRestartNotification(bool killed)
        {
            var builder = new NotificationCompat.Builder(this, MainNotifChannelId)
                          .SetContentTitle(GetString(killed ? R.String.process_is_killed : R.String.service_is_stopped))
                          .SetContentIntent(BuildIntentToShowMainActivity())
                          .AddAction(BuildServiceAction(Actions.START, R.String.start, Android.Resource.Drawable.StarOff, 6))
                          .SetSmallIcon(Resource.Drawable.N)
                          .SetColor(unchecked ((int)0xFF2196F3))
                          .SetAutoCancel(true)
                          .SetPriority((int)NotificationPriority.Min)
                          .SetVisibility(NotificationCompat.VisibilitySecret)
                          .SetShowWhen(false);

            if (!killed)
            {
                builder.AddAction(BuildServiceAction(Actions.KILL, R.String.kill, Android.Resource.Drawable.StarOff, 1));
            }
            notificationManager.Notify(MainNotificationId, builder.Build());
        }
        public Notification CreateNotification(string contentText, NotificationCompat.Action[] actions = null)
        {
            var builder = new NotificationCompat.Builder(_context, _serviceNotificationChannelId)
                          .SetContentTitle(_notificationTitle)
                          .SetContentText(contentText)
                          .SetSmallIcon(Resource.Drawable.obsidian_logo)
                          .SetContentIntent(CreateShowMainActivityIntent())
                          .SetOngoing(true)
                          .SetOnlyAlertOnce(true);

            if (actions != null)
            {
                foreach (var a in actions)
                {
                    builder.AddAction(a);
                }
            }
            return(builder.Build());
        }
        private async void ScheduleToast(Context context, MalNotification notification)
        {
            await _toastSemaphore.WaitAsync();

            var intent = new Intent(context, typeof(MainActivity));

            intent.SetAction(DateTime.Now.Ticks.ToString());
            intent.PutExtra("launchArgs", ((notification.Type == MalNotificationsTypes.UserMentions && !notification.IsSupported) ||
                                           notification.Type == MalNotificationsTypes.FriendRequest ||
                                           notification.Type == MalNotificationsTypes.ClubMessages
                                 ? "OpenUrl;"
                                 : "") + notification.LaunchArgs);
            var pendingIntent       = PendingIntent.GetActivity(context, 0, intent, PendingIntentFlags.OneShot);
            var notificationBuilder = new NotificationCompat.Builder(context)
                                      .SetSmallIcon(Resource.Drawable.ic_stat_name)
                                      .SetStyle(new NotificationCompat.BigTextStyle().BigText(notification.Content))
                                      .SetContentTitle(notification.Header)
                                      .SetContentText(notification.Content)
                                      .SetContentInfo(notification.Content)
                                      .SetAutoCancel(true)
                                      .SetGroup(notification.Type.GetDescription())
                                      .SetContentIntent(pendingIntent)
                                      .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification));

            if (notification.Type != MalNotificationsTypes.Messages &&
                notification.Type != MalNotificationsTypes.WatchedTopic)
            {
                var readIntent = new Intent(context, typeof(NotificationClickBroadcastReceiver));
                readIntent.SetAction(DateTime.Now.Ticks.ToString());
                readIntent.PutExtra(NotificationClickBroadcastReceiver.NotificationReadKey, notification.Id);
                var pendingReadIntent = PendingIntent.GetBroadcast(context, 23, readIntent, PendingIntentFlags.OneShot);
                notificationBuilder.AddAction(new NotificationCompat.Action(Resource.Drawable.icon_eye_notification, "Mark as Read",
                                                                            pendingReadIntent));
            }

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

            notificationManager.Notify(notification.Id.GetHashCode(), notificationBuilder.Build());
            await Task.Delay(500);

            _toastSemaphore.Release();
        }
Exemplo n.º 22
0
        void AddPlayPauseButton(NotificationCompat.Builder builder)
        {
            var           label = "";
            int           icon;
            PendingIntent intent;

            if (playbackState.State == PlaybackStateCompat.StatePlaying)
            {
                label  = "Pause";
                icon   = Resource.Drawable.ic_allmusic_black_24dp;
                intent = pauseIntent;
            }
            else
            {
                label  = "Play";
                icon   = Resource.Drawable.ic_allmusic_black_24dp;
                intent = playIntent;
            }
            builder.AddAction(new NotificationCompat.Action(icon, label, intent));
        }
        private Notification GetQuickUnlockNotification()
        {
            int grayIconResouceId = Resource.Drawable.ic_launcher_gray;

            if ((int)Android.OS.Build.VERSION.SdkInt < 16)
            {
                if (PreferenceManager.GetDefaultSharedPreferences(this).GetBoolean(GetString(Resource.String.QuickUnlockIconHidden_key), false))
                {
                    grayIconResouceId = Resource.Drawable.transparent;
                }
            }
            NotificationCompat.Builder builder =
                new NotificationCompat.Builder(this)
                .SetSmallIcon(grayIconResouceId)
                .SetLargeIcon(MakeLargeIcon(BitmapFactory.DecodeResource(Resources, AppNames.NotificationLockedIcon)))
                .SetVisibility((int)Android.App.NotificationVisibility.Secret)
                .SetContentTitle(GetString(Resource.String.app_name))
                .SetContentText(GetString(Resource.String.database_loaded_quickunlock_enabled, GetDatabaseName()));

            if ((int)Build.VERSION.SdkInt >= 16)
            {
                if (PreferenceManager.GetDefaultSharedPreferences(this)
                    .GetBoolean(GetString(Resource.String.QuickUnlockIconHidden16_key), true))
                {
                    builder.SetPriority((int)NotificationPriority.Min);
                }
                else
                {
                    builder.SetPriority((int)NotificationPriority.Default);
                }
            }

            // Default action is to show Kp2A
            builder.SetContentIntent(GetSwitchToAppPendingIntent());
            // Additional action to allow locking the database
            builder.AddAction(Android.Resource.Drawable.IcLockLock, GetString(Resource.String.QuickUnlock_lockButton),
                              PendingIntent.GetBroadcast(this, 0, new Intent(Intents.CloseDatabase), PendingIntentFlags.UpdateCurrent));


            return(builder.Build());
        }
Exemplo n.º 24
0
        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;

                                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);
                                }
                                else
                                {
                                    actionIntent = new Intent(context, typeof(PushNotificationActionReceiver));
                                    extras.PutString(ActionIdentifierKey, action.Id);
                                    actionIntent.PutExtras(extras);
                                    pendingActionIntent = PendingIntent.GetBroadcast(context, aRequestCode, actionIntent, PendingIntentFlags.UpdateCurrent);
                                }

                                notificationBuilder.AddAction(context.Resources.GetIdentifier(action.Icon, "drawable", Application.Context.PackageName), action.Title, pendingActionIntent);
                            }
                        }
                    }
                }
            }

            OnBuildNotification(notificationBuilder, parameters);

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

            notificationManager.Notify(tag, notifyId, notificationBuilder.Build());
        }
        public void OnReceived(IDictionary <string, object> parameters)
        {
            System.Diagnostics.Debug.WriteLine($"{DomainTag} - OnReceived");

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

            Context context = Application.Context;

            int    notifyId = 0;
            string title    = context.ApplicationInfo.LoadLabel(context.PackageManager);
            var    message  = string.Empty;
            var    tag      = string.Empty;

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

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

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

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

            if (PushNotificationManager.SoundUri == null)
            {
                PushNotificationManager.SoundUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
            }

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

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

            Intent resultIntent = context.PackageManager.GetLaunchIntentForPackage(context.PackageName);

            //Intent resultIntent = new Intent(context, typeof(T));
            Bundle extras = new Bundle();

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

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

            resultIntent.SetFlags(ActivityFlags.ClearTop);

            var pendingIntent = PendingIntent.GetActivity(context, 0, resultIntent, PendingIntentFlags.OneShot | PendingIntentFlags.UpdateCurrent);

            var notificationBuilder = new NotificationCompat.Builder(context)
                                      .SetSmallIcon(PushNotificationManager.IconResource)
                                      .SetContentTitle(title)
                                      .SetSound(PushNotificationManager.SoundUri)
                                      .SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
                                      .SetContentText(message)
                                      .SetAutoCancel(true)
                                      .SetContentIntent(pendingIntent);

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

            if (PushNotificationManager.Color != null)
            {
                notificationBuilder.SetColor(PushNotificationManager.Color.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);
            }

            string category = string.Empty;

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

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

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

            if (notificationCategories != null && notificationCategories.Length > 0)
            {
                IntentFilter intentFilter = null;
                foreach (var userCat in notificationCategories)
                {
                    if (userCat != null && userCat.Actions != null && userCat.Actions.Count > 0)
                    {
                        foreach (var action in userCat.Actions)
                        {
                            if (userCat.Category.Equals(category, StringComparison.CurrentCultureIgnoreCase))
                            {
                                Intent        actionIntent        = null;
                                PendingIntent pendingActionIntent = null;


                                if (action.Type == NotificationActionType.Foreground)
                                {
                                    actionIntent = context.PackageManager.GetLaunchIntentForPackage(context.PackageName);
                                    actionIntent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask);
                                    actionIntent.SetAction($"{action.Id}");
                                    extras.PutString(ActionIdentifierKey, action.Id);
                                    actionIntent.PutExtras(extras);
                                    pendingActionIntent = PendingIntent.GetActivity(context, 0, actionIntent, PendingIntentFlags.OneShot | PendingIntentFlags.UpdateCurrent);
                                }
                                else
                                {
                                    actionIntent = new Intent();
                                    //actionIntent.SetAction($"{category}.{action.Id}");
                                    actionIntent.SetAction($"{Application.Context.PackageManager.GetPackageInfo(Application.Context.PackageName, PackageInfoFlags.MetaData).PackageName}.{action.Id}");
                                    extras.PutString(ActionIdentifierKey, action.Id);
                                    actionIntent.PutExtras(extras);
                                    pendingActionIntent = PendingIntent.GetBroadcast(context, 0, actionIntent, PendingIntentFlags.OneShot | PendingIntentFlags.UpdateCurrent);
                                }

                                notificationBuilder.AddAction(context.Resources.GetIdentifier(action.Icon, "drawable", Application.Context.PackageName), action.Title, pendingActionIntent);
                            }


                            if (PushNotificationManager.ActionReceiver == null)
                            {
                                if (intentFilter == null)
                                {
                                    intentFilter = new IntentFilter();
                                }

                                if (!intentFilter.HasAction(action.Id))
                                {
                                    intentFilter.AddAction($"{Application.Context.PackageManager.GetPackageInfo(Application.Context.PackageName, PackageInfoFlags.MetaData).PackageName}.{action.Id}");
                                }
                            }
                        }
                    }
                }

                if (intentFilter != null)
                {
                    PushNotificationManager.ActionReceiver = new PushNotificationActionReceiver();
                    context.RegisterReceiver(PushNotificationManager.ActionReceiver, intentFilter);
                }
            }

            OnBuildNotification(notificationBuilder, parameters);

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

            notificationManager.Notify(tag, notifyId, notificationBuilder.Build());
        }
Exemplo n.º 26
0
        public virtual NotificationCompat.Builder CreateNativeBuilder(Notification notification, Channel channel)
        {
            var pendingIntent = this.GetLaunchPendingIntent(notification);
            var builder       = new NotificationCompat.Builder(this.core.Android.AppContext)
                                .SetContentTitle(notification.Title)
                                .SetSmallIcon(this.GetSmallIconResource(notification.Android.SmallIconResourceName))
                                .SetAutoCancel(notification.Android.AutoCancel)
                                .SetOngoing(notification.Android.OnGoing)
                                .SetContentIntent(pendingIntent);

            if (!notification.Android.ContentInfo.IsEmpty())
            {
                builder.SetContentInfo(notification.Android.ContentInfo);
            }

            if (!notification.Android.Ticker.IsEmpty())
            {
                builder.SetTicker(notification.Android.Ticker);
            }

            if (notification.Android.UseBigTextStyle)
            {
                builder.SetStyle(new NotificationCompat.BigTextStyle().BigText(notification.Message));
            }
            else
            {
                builder.SetContentText(notification.Message);
            }

            this.TrySetLargeIconResource(notification, builder);

            if (notification.BadgeCount != null)
            {
                builder.SetNumber(notification.BadgeCount.Value);
            }

            if (!notification.Android.ColorResourceName.IsEmpty())
            {
                var color = this.GetColor(notification.Android.ColorResourceName);
                builder.SetColor(color);
            }

            if (notification.Android.ShowWhen != null)
            {
                builder.SetShowWhen(notification.Android.ShowWhen.Value);
            }

            if (notification.Android.When != null)
            {
                builder.SetWhen(notification.Android.When.Value.ToUnixTimeMilliseconds());
            }

            builder.SetChannelId(channel.Identifier);
            if (channel.Actions != null)
            {
                foreach (var action in channel.Actions)
                {
                    switch (action.ActionType)
                    {
                    case ChannelActionType.OpenApp:
                        break;

                    case ChannelActionType.TextReply:
                        var textReplyAction = this.CreateTextReply(notification, action);
                        builder.AddAction(textReplyAction);
                        break;

                    case ChannelActionType.None:
                    case ChannelActionType.Destructive:
                        var destAction = this.CreateAction(notification, action);
                        builder.AddAction(destAction);
                        break;

                    default:
                        throw new ArgumentException("Invalid action type");
                    }
                }
            }
            return(builder);
        }
Exemplo n.º 27
0
        private Notification GetQuickUnlockNotification()
        {
            int grayIconResouceId = Resource.Drawable.ic_launcher_gray;
            if ((int)Android.OS.Build.VERSION.SdkInt < 16)
            if (PreferenceManager.GetDefaultSharedPreferences(this).GetBoolean(GetString(Resource.String.QuickUnlockIconHidden_key), false))
            {
                grayIconResouceId = Resource.Drawable.transparent;
            }
            NotificationCompat.Builder builder =
                new NotificationCompat.Builder(this)
                    .SetSmallIcon(grayIconResouceId)
                    .SetLargeIcon(MakeLargeIcon(BitmapFactory.DecodeResource(Resources, AppNames.NotificationLockedIcon)))
                    .SetVisibility((int)Android.App.NotificationVisibility.Secret)
                    .SetContentTitle(GetString(Resource.String.app_name))
                    .SetContentText(GetString(Resource.String.database_loaded_quickunlock_enabled, GetDatabaseName()));

            if ((int)Build.VERSION.SdkInt >= 16)
            {
                if (PreferenceManager.GetDefaultSharedPreferences(this)
                                 .GetBoolean(GetString(Resource.String.QuickUnlockIconHidden16_key), true))
                {
                    builder.SetPriority((int) NotificationPriority.Min);
                }
                else
                {
                    builder.SetPriority((int)NotificationPriority.Default);
                }
            }

            // Default action is to show Kp2A
            builder.SetContentIntent(GetSwitchToAppPendingIntent());
            // Additional action to allow locking the database
            builder.AddAction(Android.Resource.Drawable.IcLockLock, GetString(Resource.String.QuickUnlock_lockButton),
                PendingIntent.GetBroadcast(this, 0, new Intent(Intents.CloseDatabase), PendingIntentFlags.UpdateCurrent));

            return builder.Build();
        }
Exemplo n.º 28
0
        public void OnReceived(IDictionary <string, object> parameters)
        {
            System.Diagnostics.Debug.WriteLine($"{DomainTag} - OnReceived");

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

            Context context = Application.Context;

            int    notifyId = 0;
            string title    = context.ApplicationInfo.LoadLabel(context.PackageManager);
            var    message  = string.Empty;
            var    tag      = string.Empty;

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

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

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

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

            try
            {
                if (parameters.TryGetValue(SoundKey, out object sound))
                {
                    var soundName = sound.ToString();

                    int 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);
                    }

                    FirebasePushNotificationManager.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 (FirebasePushNotificationManager.SoundUri == null)
            {
                FirebasePushNotificationManager.SoundUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
            }

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

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

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

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

            Bundle extras = new Bundle();

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

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

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

            var pendingIntent = PendingIntent.GetActivity(context, requestCode, resultIntent, PendingIntentFlags.UpdateCurrent);

            var chanId = FirebasePushNotificationManager.DefaultNotificationChannelId;

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

            var notificationBuilder = new NotificationCompat.Builder(context, chanId)
                                      .SetSmallIcon(FirebasePushNotificationManager.IconResource)
                                      .SetContentTitle(title)
                                      .SetContentText(message)
                                      .SetAutoCancel(true)
                                      .SetContentIntent(pendingIntent);

            var deleteIntent        = new Intent(context, typeof(PushNotificationDeletedReceiver));
            var pendingDeleteIntent = PendingIntent.GetBroadcast(context, requestCode, deleteIntent, PendingIntentFlags.CancelCurrent);

            notificationBuilder.SetDeleteIntent(pendingDeleteIntent);

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

                        case "high":
                            notificationBuilder.SetPriority((int)Android.App.NotificationPriority.High);
                            notificationBuilder.SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
                            break;

                        case "default":
                            notificationBuilder.SetPriority((int)Android.App.NotificationPriority.Default);
                            notificationBuilder.SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
                            break;

                        case "low":
                            notificationBuilder.SetPriority((int)Android.App.NotificationPriority.Low);
                            break;

                        case "min":
                            notificationBuilder.SetPriority((int)Android.App.NotificationPriority.Min);
                            break;

                        default:
                            notificationBuilder.SetPriority((int)Android.App.NotificationPriority.Default);
                            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(FirebasePushNotificationManager.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 (FirebasePushNotificationManager.Color != null)
            {
                notificationBuilder.SetColor(FirebasePushNotificationManager.Color.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);
            }

            string category = string.Empty;

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

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

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

            if (notificationCategories != null && notificationCategories.Length > 0)
            {
                IntentFilter intentFilter = null;
                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;


                                if (action.Type == NotificationActionType.Foreground)
                                {
                                    actionIntent = typeof(Activity).IsAssignableFrom(FirebasePushNotificationManager.NotificationActivityType) ? new Intent(Application.Context, FirebasePushNotificationManager.NotificationActivityType) : (FirebasePushNotificationManager.DefaultNotificationActivityType == null ? context.PackageManager.GetLaunchIntentForPackage(context.PackageName) : new Intent(Application.Context, FirebasePushNotificationManager.DefaultNotificationActivityType));

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

                                    extras.PutString(ActionIdentifierKey, action.Id);
                                    actionIntent.PutExtras(extras);
                                    pendingActionIntent = PendingIntent.GetActivity(context, aRequestCode, actionIntent, PendingIntentFlags.UpdateCurrent);
                                }
                                else
                                {
                                    actionIntent = new Intent(context, typeof(PushNotificationActionReceiver));
                                    extras.PutString(ActionIdentifierKey, action.Id);
                                    actionIntent.PutExtras(extras);
                                    pendingActionIntent = PendingIntent.GetBroadcast(context, aRequestCode, actionIntent, PendingIntentFlags.UpdateCurrent);
                                }

                                notificationBuilder.AddAction(new NotificationCompat.Action.Builder(context.Resources.GetIdentifier(action.Icon, "drawable", Application.Context.PackageName), action.Title, pendingActionIntent).Build());
                            }
                        }
                    }
                }
            }

            OnBuildNotification(notificationBuilder, parameters);

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

            notificationManager.Notify(tag, notifyId, notificationBuilder.Build());
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="request"></param>
        protected virtual async Task <bool> ShowNow(NotificationRequest request)
        {
            if (string.IsNullOrWhiteSpace(request.Android.ChannelId))
            {
                request.Android.ChannelId = AndroidOptions.DefaultChannelId;
            }

            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                var channel = MyNotificationManager.GetNotificationChannel(request.Android.ChannelId);
                if (channel is null)
                {
                    NotificationCenter.CreateNotificationChannel(new NotificationChannelRequest
                    {
                        Id = request.Android.ChannelId
                    });
                }
            }

            using var builder = new NotificationCompat.Builder(Application.Context, request.Android.ChannelId);
            builder.SetContentTitle(request.Title);
            builder.SetSubText(request.Subtitle);
            builder.SetContentText(request.Description);
            if (request.Image != null && request.Image.HasValue)
            {
                var imageBitmap = await GetNativeImage(request.Image);

                if (imageBitmap != null)
                {
                    using var picStyle = new NotificationCompat.BigPictureStyle();
                    picStyle.BigPicture(imageBitmap);
                    picStyle.SetSummaryText(request.Subtitle);
                    builder.SetStyle(picStyle);
                }
            }
            else
            {
                if (string.IsNullOrWhiteSpace(request.Description) == false)
                {
                    using var bigTextStyle = new NotificationCompat.BigTextStyle();
                    bigTextStyle.BigText(request.Description);
                    bigTextStyle.SetSummaryText(request.Subtitle);
                    builder.SetStyle(bigTextStyle);
                }
            }
            builder.SetNumber(request.BadgeNumber);
            builder.SetAutoCancel(request.Android.AutoCancel);
            builder.SetOngoing(request.Android.Ongoing);

            if (string.IsNullOrWhiteSpace(request.Android.Group) == false)
            {
                builder.SetGroup(request.Android.Group);
                if (request.Android.IsGroupSummary)
                {
                    builder.SetGroupSummary(true);
                }
            }

            if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
            {
                if (request.CategoryType != NotificationCategoryType.None)
                {
                    builder.SetCategory(ToNativeCategory(request.CategoryType));
                }

                builder.SetVisibility(ToNativeVisibilityType(request.Android.VisibilityType));
            }

            if (Build.VERSION.SdkInt < BuildVersionCodes.O)
            {
                builder.SetPriority((int)request.Android.Priority);

                var soundUri = NotificationCenter.GetSoundUri(request.Sound);
                if (soundUri != null)
                {
                    builder.SetSound(soundUri);
                }
            }

            if (request.Android.VibrationPattern != null)
            {
                builder.SetVibrate(request.Android.VibrationPattern);
            }

            if (request.Android.ProgressBarMax.HasValue &&
                request.Android.ProgressBarProgress.HasValue &&
                request.Android.IsProgressBarIndeterminate.HasValue)
            {
                builder.SetProgress(request.Android.ProgressBarMax.Value,
                                    request.Android.ProgressBarProgress.Value,
                                    request.Android.IsProgressBarIndeterminate.Value);
            }

            if (request.Android.Color != null)
            {
                if (request.Android.Color.Argb.HasValue)
                {
                    builder.SetColor(request.Android.Color.Argb.Value);
                }
                else if (string.IsNullOrWhiteSpace(request.Android.Color.ResourceName) == false)
                {
                    var colorResourceId = Application.Context.Resources?.GetIdentifier(request.Android.Color.ResourceName, "color", Application.Context.PackageName) ?? 0;
                    var colorId         = Application.Context.GetColor(colorResourceId);
                    builder.SetColor(colorId);
                }
            }

            builder.SetSmallIcon(GetIcon(request.Android.IconSmallName));
            if (request.Android.IconLargeName != null && string.IsNullOrWhiteSpace(request.Android.IconLargeName.ResourceName) == false)
            {
                var largeIcon = await BitmapFactory.DecodeResourceAsync(Application.Context.Resources, GetIcon(request.Android.IconLargeName));

                if (largeIcon != null)
                {
                    builder.SetLargeIcon(largeIcon);
                }
            }

            if (request.Android.TimeoutAfter.HasValue)
            {
                builder.SetTimeoutAfter((long)request.Android.TimeoutAfter.Value.TotalMilliseconds);
            }

            var notificationIntent = Application.Context.PackageManager?.GetLaunchIntentForPackage(Application.Context.PackageName ?? string.Empty);

            if (notificationIntent is null)
            {
                Log($"NotificationServiceImpl.ShowNow: notificationIntent is null");
                return(false);
            }

            var serializedRequest = JsonSerializer.Serialize(request);

            notificationIntent.SetFlags(ActivityFlags.SingleTop);
            notificationIntent.PutExtra(NotificationCenter.ReturnRequest, serializedRequest);

            var pendingIntent = PendingIntent.GetActivity(Application.Context, request.NotificationId, notificationIntent,
                                                          PendingIntentFlags.CancelCurrent);

            builder.SetContentIntent(pendingIntent);

            if (_categoryList.Any())
            {
                var categoryByType = _categoryList.FirstOrDefault(c => c.CategoryType == request.CategoryType);
                if (categoryByType != null)
                {
                    foreach (var notificationAction in categoryByType.ActionList)
                    {
                        var nativeAction = CreateAction(request, serializedRequest, notificationAction);
                        if (nativeAction is null)
                        {
                            continue;
                        }
                        builder.AddAction(nativeAction);
                    }
                }
            }

            var notification = builder.Build();

            if (Build.VERSION.SdkInt < BuildVersionCodes.O &&
                request.Android.LedColor.HasValue)
            {
#pragma warning disable 618
                notification.LedARGB = request.Android.LedColor.Value;
#pragma warning restore 618
            }

            if (Build.VERSION.SdkInt < BuildVersionCodes.O &&
                string.IsNullOrWhiteSpace(request.Sound))
            {
#pragma warning disable 618
                notification.Defaults = NotificationDefaults.All;
#pragma warning restore 618
            }
            MyNotificationManager?.Notify(request.NotificationId, notification);

            var args = new NotificationEventArgs
            {
                Request = request
            };
            NotificationCenter.Current.OnNotificationReceived(args);

            AddPreferencesNotificationId(PreferencesDeliveredIdListKey, request.NotificationId);

            return(true);
        }
Exemplo n.º 30
0
        private Notification GetUnlockedNotification()
        {
            NotificationCompat.Builder builder =
                new NotificationCompat.Builder(this)
                    .SetOngoing(true)
                    .SetSmallIcon(Resource.Drawable.ic_notify)
                    .SetLargeIcon(MakeLargeIcon(BitmapFactory.DecodeResource(Resources, AppNames.NotificationUnlockedIcon)))
                    .SetVisibility((int)Android.App.NotificationVisibility.Public)
                    .SetContentTitle(GetString(Resource.String.app_name))
                    .SetContentText(GetString(Resource.String.database_loaded_unlocked, GetDatabaseName()));

            if ((int)Build.VERSION.SdkInt >= 16)
            {
                if (PreferenceManager.GetDefaultSharedPreferences(this)
                                 .GetBoolean(GetString(Resource.String.ShowUnlockedNotification_key),
                                             Resources.GetBoolean(Resource.Boolean.ShowUnlockedNotification_default)))
                {
                    builder.SetPriority((int)NotificationPriority.Default);
                }
                else
                {
                    builder.SetPriority((int) NotificationPriority.Min);
                }
            }

            // Default action is to show Kp2A
            builder.SetContentIntent(GetSwitchToAppPendingIntent());
            // Additional action to allow locking the database
            builder.AddAction(Resource.Drawable.ic_action_lock, GetString(Resource.String.menu_lock), PendingIntent.GetBroadcast(this, 0, new Intent(Intents.LockDatabase), PendingIntentFlags.UpdateCurrent));

            return builder.Build();
        }
        /// <summary>
        /// When we start on the foreground we will present a notification to the user
        /// When they press the notification it will take them to the main page so they can control the music
        /// </summary>
        private void StartNotification ()
        {
            if (mediaSessionCompat == null)
                return;

            var pendingIntent = PendingIntent.GetActivity(ApplicationContext, 0, new Intent(ApplicationContext, typeof(MainActivity)), PendingIntentFlags.UpdateCurrent);
            MediaMetadataCompat currentTrack = mediaControllerCompat.Metadata;

            Android.Support.V7.App.NotificationCompat.MediaStyle style = new Android.Support.V7.App.NotificationCompat.MediaStyle();
            style.SetMediaSession(mediaSessionCompat.SessionToken);

            Intent intent = new Intent(ApplicationContext, typeof(MediaPlayerService));
            intent.SetAction(ActionStop);
            PendingIntent pendingCancelIntent = PendingIntent.GetService(ApplicationContext, 1, intent, PendingIntentFlags.CancelCurrent);

            style.SetShowCancelButton(true);
            style.SetCancelButtonIntent(pendingCancelIntent);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(ApplicationContext)
                .SetStyle(style)
                .SetContentTitle (currentTrack.GetString(MediaMetadata.MetadataKeyTitle))
                .SetContentText (currentTrack.GetString(MediaMetadata.MetadataKeyArtist))
                .SetContentInfo (currentTrack.GetString(MediaMetadata.MetadataKeyAlbum))
                .SetSmallIcon (Resource.Drawable.album_art)
                .SetLargeIcon (Cover as Bitmap)
                .SetContentIntent(pendingIntent)
                .SetShowWhen(false)
                .SetOngoing(MediaPlayerState == PlaybackStateCompat.StatePlaying)
                .SetVisibility(NotificationCompat.VisibilityPublic);

            builder.AddAction(GenerateActionCompat(Android.Resource.Drawable.IcMediaPrevious, "Previous", ActionPrevious));
            AddPlayPauseActionCompat(builder);
            builder.AddAction(GenerateActionCompat(Android.Resource.Drawable.IcMediaNext, "Next", ActionNext));
            style.SetShowActionsInCompactView(0, 1, 2);

            NotificationManagerCompat.From(ApplicationContext).Notify(NotificationId, builder.Build());
        }
Exemplo n.º 32
0
        Notification CreateNotification()
        {
            if (metadata == null || playbackState == null)
            {
                return(null);
            }

            var notificationBuilder = new NotificationCompat.Builder(Service);
            var playButtonPosition  = 0;

            if ((playbackState.Actions & PlaybackStateCompat.ActionSkipToPrevious) != 0)
            {
                notificationBuilder.AddAction(Resource.Drawable.ic_skip_previous_white_24dp, "Previous", previousIntent);
                playButtonPosition = 1;
            }

            AddPlayPauseButton(notificationBuilder);

            if ((playbackState.Actions & PlaybackStateCompat.ActionSkipToNext) != 0)
            {
                notificationBuilder.AddAction(Resource.Drawable.ic_skip_next_white_24dp, "Next", nextIntent);
            }

            var    description = metadata.Description;
            string fetchArtUrl = null;
            Bitmap art         = null;

            if (description.IconUri != null)
            {
                var artUrl = description.IconUri.ToString();
                //TODO: get art from cache
                if (art == null)
                {
                    fetchArtUrl = artUrl;
                    art         = BitmapFactory.DecodeResource(Service.Resources, Resource.Drawable.ic_default_art);
                }
            }
            else
            {
                art = BitmapFactory.DecodeResource(Service.Resources, Resource.Drawable.ic_default_art);
            }

            notificationBuilder.SetStyle(new Android.Support.V7.App.NotificationCompat.MediaStyle()
                                         .SetShowActionsInCompactView(new[] { playButtonPosition }).SetMediaSession(sessionToken))
            .SetColor(notificationColor)
            .SetSmallIcon(Resource.Drawable.ic_notification)
            .SetVisibility(NotificationCompat.VisibilityPublic)
            .SetUsesChronometer(true)
            .SetContentIntent(CreateContentIntent(description))
            .SetContentTitle(description.Title)
            .SetContentText(description.Subtitle)
            .SetLargeIcon(art);

            if (controller != null && controller.Extras != null)
            {
                var castName = controller.Extras.GetString(MusicService.ExtraConnectedCast);
                if (string.IsNullOrWhiteSpace(castName))
                {
                    var castInfo = $"Casting to {castName}";
                    notificationBuilder.SetSubText(castInfo);
                    notificationBuilder.AddAction(Resource.Drawable.ic_close_black_24dp, "Stop Casting", stopCastingIntent);
                }
            }

            SetNotificationPlaybackState(notificationBuilder);

            if (!string.IsNullOrWhiteSpace(fetchArtUrl))
            {
                //TODO: Fetch url
            }

            return(notificationBuilder.Build());
        }
Exemplo n.º 33
0
        private void SetNotificationAction(NotificationCompat.Builder notificationBuilder, IDictionary <string, object> parameters, Bundle extras)
        {
            string category = string.Empty;

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

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

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

            var notificationCategories = CrossFirebaseEssentials.Notifications?.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;
                                PendingIntent pendingActionIntent;

                                if (action.Type == NotificationActionType.Foreground)
                                {
                                    actionIntent = typeof(Activity).IsAssignableFrom(FirebasePushNotificationManager.NotificationActivityType) ? new Intent(Application.Context, FirebasePushNotificationManager.NotificationActivityType) : (FirebasePushNotificationManager.DefaultNotificationActivityType == null ? context.PackageManager.GetLaunchIntentForPackage(context.PackageName) : new Intent(Application.Context, FirebasePushNotificationManager.DefaultNotificationActivityType));

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

                                    extras.PutString(ActionIdentifierKey, action.Id);
                                    actionIntent.PutExtras(extras);
                                    pendingActionIntent = PendingIntent.GetActivity(context, aRequestCode, actionIntent, PendingIntentFlags.UpdateCurrent);
                                }
                                else
                                {
                                    actionIntent = new Intent(context, typeof(PushNotificationActionReceiver));
                                    extras.PutString(ActionIdentifierKey, action.Id);
                                    actionIntent.PutExtras(extras);
                                    pendingActionIntent = PendingIntent.GetBroadcast(context, aRequestCode, actionIntent, PendingIntentFlags.UpdateCurrent);
                                }

                                notificationBuilder.AddAction(new NotificationCompat.Action.Builder(context.Resources.GetIdentifier(action.Icon, "drawable", Application.Context.PackageName), action.Title, pendingActionIntent).Build());
                            }
                        }
                    }
                }
            }
        }