Example #1
0
 private static string CheckRequiredParams(Context context, Bundle bundle, string type)
 {
     if (GetActivityClass(context) == null)
     {
         return("Activity is required!");
     }
     else if (bundle.GetString(NotificationConstants.Message) == null)
     {
         return("Notification Message is required!");
     }
     else if (!bundle.ContainsKey(NotificationConstants.Id))
     {
         bundle.PutInt(NotificationConstants.Id, CoreUtils.GetRandomInt());
         return(Success);
     }
     else if (type == CoreConstants.NotificationType.Scheduled && bundle.GetDouble(NotificationConstants.FireDate) == 0)
     {
         return("Fire Date is required for schedule!");
     }
     return(Success);
 }
Example #2
0
        /// <summary>
        /// Pushes a local notification instantly.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="bundle"></param>
        /// <returns></returns>
        public static async System.Threading.Tasks.Task LocalNotificationNow(Context context, Bundle bundle)
        {
            try
            {
                string requiredParams = CheckRequiredParams(context, bundle, CoreConstants.NotificationType.Now);
                if (requiredParams != Success)
                {
                    throw new System.Exception(requiredParams);
                }

                string channelId  = bundle.GetString(NotificationConstants.ChannelId, CoreConstants.NotificationChannelId);
                int    priority   = bundle.GetPriority();
                int    importance = bundle.GetImportance();
                int    visibility = bundle.GetVisibility();

                channelId += '-' + importance;


                int    smallIcon          = bundle.GetInt(NotificationConstants.SmallIcon);
                bool   isOngoing          = bundle.GetBoolean(NotificationConstants.Ongoing, false);
                bool   isOnlyAlertOnce    = bundle.GetBoolean(NotificationConstants.OnlyAlertOnce, false);
                bool   isAutoCancel       = bundle.GetBoolean(NotificationConstants.AutoCancel, true);
                bool   isGroupSummary     = bundle.GetBoolean(NotificationConstants.GroupSummary, false);
                bool   showWhen           = bundle.GetBoolean(NotificationConstants.ShowWhen, true);
                string ticker             = bundle.GetString(NotificationConstants.Ticker, "Optional Ticker");
                string channelDescription = bundle.GetString(NotificationConstants.ChannelDescription, string.Empty);
                string channelName        = bundle.GetString(NotificationConstants.ChannelName, CoreConstants.ChannelName);
                string message            = bundle.GetString(NotificationConstants.Message, string.Empty);
                string title   = bundle.GetString(NotificationConstants.Title, string.Empty);
                string bigText = bundle.GetString(NotificationConstants.BigText, string.Empty);
                bigText ??= message;

                // Instantiate the builder and set notification elements:
                NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "")
                                                     .SetVisibility(visibility)
                                                     .SetContentTitle(title)
                                                     .SetContentText(message)
                                                     .SetSmallIcon(smallIcon)
                                                     .SetPriority(priority)
                                                     .SetTicker(ticker)
                                                     .SetAutoCancel(isAutoCancel)
                                                     .SetOnlyAlertOnce(isOnlyAlertOnce)
                                                     .SetOngoing(isOngoing);

                if (bundle.ContainsKey(NotificationConstants.Number))
                {
                    builder.SetBadgeIconType(NotificationCompat.BadgeIconSmall);
                    builder.SetNumber(bundle.GetInt(NotificationConstants.Number));
                }

                //Big Picture Url
                if (bundle.ContainsKey(NotificationConstants.BigPictureUrl))
                {
                    Bitmap bitmap = await Utils.Utils.GetBitmapFromUrlAsync(bundle.GetString(NotificationConstants.BigPictureUrl));

                    NotificationCompat.BigPictureStyle style = new NotificationCompat.BigPictureStyle();
                    style.BigPicture(bitmap);
                    builder.SetStyle(style);
                }
                else
                {
                    NotificationCompat.Style style = new NotificationCompat.BigTextStyle().BigText(bigText);
                    builder.SetStyle(style);
                }

                //Large Icon Url
                if (bundle.GetString(NotificationConstants.LargeIconUrl) != null)
                {
                    Bitmap largeIconBitmap = await Utils.Utils.GetBitmapFromUrlAsync(bundle.GetString(NotificationConstants.LargeIconUrl));

                    builder.SetLargeIcon(largeIconBitmap);
                }
                else if (bundle.GetInt(NotificationConstants.LargeIcon, -1) != -1)
                {
                    builder.SetLargeIcon(BitmapFactory.DecodeResource(context.Resources, bundle.GetInt(NotificationConstants.LargeIcon)));
                }

                //Vibrate
                long[] vibratePattern = new long[] { 0 };
                if (bundle.GetBoolean(NotificationConstants.Vibrate, false))
                {
                    long vibrateDuration = bundle.ContainsKey(NotificationConstants.VibrateDuration) ?
                                           bundle.GetLong(NotificationConstants.VibrateDuration) : CoreConstants.DefaultVibrateDuration;
                    vibratePattern = new long[] { 0, vibrateDuration };
                    builder.SetVibrate(vibratePattern);

                    channelId += '-' + vibrateDuration;
                }

                //SubText
                string subText = bundle.GetString(NotificationConstants.SubText);
                if (subText != string.Empty)
                {
                    builder.SetSubText(subText);
                }

                //Sound
                Uri soundUri = null;
                if (bundle.GetBoolean(NotificationConstants.PlaySound, false))
                {
                    soundUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification);

                    string soundName = bundle.GetString(NotificationConstants.SoundName);
                    if (soundName != null)
                    {
                        int resId;
                        if (context.Resources.GetIdentifier(soundName, null, null) == 0)
                        {
                            soundName = soundName.Substring(0, soundName.LastIndexOf('.'));
                        }
                        resId    = context.Resources.GetIdentifier(context.PackageName + ":drawable/" + soundName, null, null);
                        soundUri = Uri.Parse($"{ ContentResolver.SchemeAndroidResource}://{context.PackageName}/{resId}");
                    }

                    channelId += '-' + soundName;
                }

                //ShowWhen
                if (Build.VERSION.SdkInt >= BuildVersionCodes.N)
                {
                    builder.SetShowWhen(showWhen);
                }

                //Defaults
                if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
                {
                    builder.SetDefaults(NotificationCompat.FlagShowLights);
                }

                //Group and GroupSummary
                if (Build.VERSION.SdkInt >= BuildVersionCodes.KitkatWatch)
                {
                    string group = bundle.GetString(NotificationConstants.Group);

                    if (group != null)
                    {
                        builder.SetGroup(group);
                    }

                    if (bundle.ContainsKey(NotificationConstants.GroupSummary) || isGroupSummary)
                    {
                        builder.SetGroupSummary(isGroupSummary);
                    }
                }

                //Category Color
                if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
                {
                    builder.SetCategory(NotificationCompat.CategoryCall);

                    string color = bundle.GetString(NotificationConstants.Color);
                    if (color != null)
                    {
                        builder.SetColor(Color.ParseColor(color));
                    }
                }

                int notificationId = bundle.GetInt(NotificationConstants.Id, CoreUtils.GetRandomInt());
                bundle.PutInt(NotificationConstants.Id, notificationId);

                Class intentClass = Class.ForName(context.PackageManager.GetLaunchIntentForPackage(context.PackageName).Component.ClassName);

                Intent intent = new Intent(context, intentClass);
                intent.AddFlags(ActivityFlags.SingleTop);
                intent.PutExtra(NotificationConstants.Notification, bundle);

                PendingIntent pendingIntent = PendingIntent.GetActivity(context, notificationId, intent,
                                                                        PendingIntentFlags.UpdateCurrent);

                CreateNotificationChannel(context, channelId, channelName, channelDescription, soundUri, (NotificationImportance)importance, vibratePattern);
                builder.SetChannelId(channelId);
                builder.SetContentIntent(pendingIntent);

                string[] actionArr = null;
                try
                {
                    if (bundle.ContainsKey(NotificationConstants.Actions))
                    {
                        actionArr = bundle.GetStringArray(NotificationConstants.Actions);
                    }
                }
                catch { }
                if (actionArr != null)
                {
                    int icon = 0;

                    for (int i = 0; i < actionArr.Length; i++)
                    {
                        string action;
                        try
                        {
                            action = actionArr[i];
                        }
                        catch
                        {
                            continue;
                        }
                        Class  cls          = Class.FromType(typeof(HmsLocalNotificationActionsReceiver));
                        Intent actionIntent = new Intent(context, cls);
                        actionIntent.SetAction(context.PackageName + ".ACTION_" + i);

                        actionIntent.AddFlags(ActivityFlags.SingleTop);

                        bundle.PutString(NotificationConstants.Action, action);
                        actionIntent.PutExtra(NotificationConstants.Notification, bundle);
                        actionIntent.SetPackage(context.PackageName);

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


                        if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
                        {
                            builder.AddAction(new NotificationCompat.Action.Builder(icon, action, pendingActionIntent).Build());
                        }
                        else
                        {
                            builder.AddAction(icon, action, pendingActionIntent);
                        }
                    }
                }


                // Build the notification:
                Notification notification = builder.Build();

                ISharedPreferences sharedPreferences = context.GetSharedPreferences(CoreConstants.PreferenceName, FileCreationMode.Private);
                string             id = bundle.GetInt(NotificationConstants.Id).ToString();
                if (sharedPreferences.GetString(id, null) != null)
                {
                    ISharedPreferencesEditor editor = sharedPreferences.Edit();
                    editor.Remove(bundle.GetInt(NotificationConstants.Id).ToString());
                    editor.Apply();
                }

                // Publish the notification:
                if (!(Utils.Utils.IsApplicationInForeground(context) && bundle.GetBoolean(NotificationConstants.DontNotifyInForeground, false)))
                {
                    string tag = bundle.GetString(NotificationConstants.Tag);
                    if (tag != string.Empty && tag != null)
                    {
                        Utils.Utils.GetNotificationManager(context).Notify(tag, notificationId, notification);
                    }
                    else
                    {
                        Utils.Utils.GetNotificationManager(context).Notify(notificationId, notification);
                    }
                }
                LocalNotificationRepeat(context, bundle);

                Log.Info("LocalNotificationNow", Success + bundle.ToJsonObject().ToString());
                return;
            }
            catch (System.Exception e)
            {
                Log.Error("LocalNotificationNow", e.ToString());
                throw e;
            }
        }