Example #1
0
        private async Task <int> Notify(AsyncNetwork network, string title, string message)
        {
            Setting setting = db.Table <Setting> ().FirstOrDefault();

            if (!setting.Notifications)
            {
                return(0);
            }

            // Set up an intent so that tapping the notifications returns to this app:
            Intent intent = new Intent(this, typeof(MainActivity));

            // Create a PendingIntent; we're only using one PendingIntent (ID = 0):
            const int     pendingIntentId = 0;
            PendingIntent pendingIntent   =
                PendingIntent.GetActivity(this, pendingIntentId, intent, PendingIntentFlags.OneShot);
            var msg = message;

            if (msg.StartsWith("#image"))
            {
                msg = "You received an image.";
            }
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                                                 .SetContentIntent(pendingIntent)
                                                 .SetContentTitle(title)
                                                 .SetContentText(msg)
                                                 .SetAutoCancel(true)
                                                 .SetSmallIcon(Resource.Drawable.Icon);

            if (setting.Sound)
            {
                builder.SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification));
            }


            if ((int)Android.OS.Build.VERSION.SdkInt >= 14)
            {
                if (setting.Led)
                {
                    builder.SetLights(Android.Graphics.Color.Magenta, 500, 500);
                }
                if (message.StartsWith("#image"))
                {
                    // Instantiate the Image (Big Picture) style:
                    NotificationCompat.BigPictureStyle picStyle = new NotificationCompat.BigPictureStyle();

                    // Convert the image to a bitmap before passing it into the style:
                    picStyle.BigPicture(await network.GetImageBitmapFromUrlNoCache(message.Substring("#image ".Length), AsyncNetwork.IMAGE_SIZE, AsyncNetwork.IMAGE_SIZE));

                    // Set the summary text that will appear with the image:
                    picStyle.SetSummaryText(msg);

                    // Plug this style into the builder:
                    builder.SetStyle(picStyle);
                }
                else
                {
                    NotificationCompat.BigTextStyle textStyle = new NotificationCompat.BigTextStyle();

                    // Fill it with text:
                    textStyle.BigText(message);

                    // Set the summary text:
                    textStyle.SetSummaryText("New message");
                    builder.SetStyle(textStyle);
                }
            }

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

            // Get the notification manager:
            NotificationManager notificationManager =
                GetSystemService(Context.NotificationService) as NotificationManager;

            // Publish the notification:
            const int notificationId = 0;

            notificationManager.Notify(notificationId, notification);

            if (setting.Vibrate)
            {
                Vibrator v = (Vibrator)GetSystemService(Context.VibratorService);                  // Make phone vibrate
                v.Vibrate(300);
            }

            return(notificationId);
        }
        public async 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")))
            {
                return;
            }

            var context = Application.Context;

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

            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(TypeKey, out var typeStr))
            {
                type = $"{typeStr}";

                switch (type)
                {
                case AppConstants.FCM.Types.Message:
                case AppConstants.FCM.Types.GroupMessage:
                    if (parameters.TryGetValue(DataKey, out var data))
                    {
                        try
                        {
                            var chatMessage   = JsonConvert.DeserializeObject <ChatMessage>($"{data}");
                            var walletManager = (WalletManager)App.Current.Container.Resolve(typeof(WalletManager));

                            if (chatMessage.Sender.TronAddress == walletManager.Wallet.Address)
                            {
                                return;
                            }

                            chatMessage.Decrypt(walletManager.Wallet, chatMessage.Sender.PublicKey);

                            if (chatMessage.ExtendedMessage == null)
                            {
                                var database = (ConverseDatabase)App.Current.Container.Resolve(typeof(ConverseDatabase));
                                var dbChat   = await database.Chats.GetByChatID(notifyId);

                                if (dbChat != null)
                                {
                                    var chat = dbChat.ToChatEntry();
                                    if (chat.Type == Enums.ChatType.Group)
                                    {
                                        var privKey = chat.GroupInfo.IsPublic ? chat.GroupInfo.PrivateKey : walletManager.Wallet.Decrypt(chat.GroupInfo.PrivateKey, chat.GroupInfo.PublicKey);
                                        chatMessage.Decrypt(privKey, chatMessage.Sender.PublicKey);
                                    }
                                }
                            }

                            message = chatMessage.ExtendedMessage.Message;
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine(ex);
                        }
                    }
                    break;

                default:
                    break;
                }
            }


            if (message == null)
            {
                if (!string.IsNullOrEmpty(FirebasePushNotificationManager.NotificationContentTextKey) && parameters.TryGetValue(FirebasePushNotificationManager.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}";
                }
                else
                {
                    message = string.Empty;
                }
            }

            if (!string.IsNullOrEmpty(FirebasePushNotificationManager.NotificationContentTitleKey) && parameters.TryGetValue(FirebasePushNotificationManager.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(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(".", StringComparison.Ordinal) != -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 (Android.Content.Res.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 var icon) && icon != null)
                {
                    try
                    {
                        FirebasePushNotificationManager.IconResource = context.Resources.GetIdentifier(icon.ToString(), "drawable", Application.Context.PackageName);
                    }
                    catch (Android.Content.Res.Resources.NotFoundException ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex.ToString());
                    }
                }

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

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

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

            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 (FirebasePushNotificationManager.NotificationActivityFlags != null)
            {
                resultIntent.SetFlags(FirebasePushNotificationManager.NotificationActivityFlags.Value);
            }
            var requestCode = new Java.Util.Random().NextInt();

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

            var chanId = FirebasePushNotificationManager.DefaultNotificationChannelId;

            if (parameters.TryGetValue(ChannelIdKey, out var 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 var 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}");
                }
            }


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

            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 = 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) : context.PackageManager.GetLaunchIntentForPackage(context.PackageName);

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

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

            notificationManager.Notify(tag, notifyId, notificationBuilder.Build());
        }
        public void InitSystemSound()
        {
            var uri = RingtoneManager.GetDefaultUri(RingtoneType.Ringtone);

            rt = RingtoneManager.GetRingtone(MainActivity.instance.ApplicationContext, uri);
        }
Example #4
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Settings);
            var toolbar = FindViewById <Toolbar>(Resource.Id.toolbar);

            SetSupportActionBar(toolbar);
            SupportActionBar.SetDisplayHomeAsUpEnabled(true);
            SupportActionBar.SetDisplayShowHomeEnabled(true);
            SupportActionBar.Title = "Ustawienia";

            HoursList = FindViewById <MedicationDosageTimeLayout>(Resource.Id.hoursList);
            HoursList.ItemTemplateId = Resource.Layout.time_item;

            addHour = FindViewById <TextView>(Resource.Id.addHourBtn);
            var hoursAdapter = (MedicationDosageTimeListAdapter)HoursList.Adapter;

            hoursAdapter.CLickItem.Subscribe(item =>
            {
                TimePickerDialog timePicker = new TimePickerDialog(
                    this,
                    (s, args) =>
                {
                    if (((TimePicker)s).IsShown)
                    {
                        newItem      = new TimeItem(item.Name);
                        newItem.Hour = new TimeSpan(args.HourOfDay, args.Minute, 0);
                        var id       = this.ViewModel.HoursList.IndexOf(item);
                        if (id >= 0)
                        {
                            this.ViewModel.HoursList.RemoveAt(id);
                            this.ViewModel.HoursList.Insert(id, newItem);
                        }
                    }
                },
                    item.Hour.Hours,
                    item.Hour.Minutes,
                    true);
                timePicker.Show();
            });

            hoursAdapter.DeleteRequested.Subscribe(time => this.ViewModel.HoursList.Remove(time));

            soundLabel        = FindViewById <TextView>(Resource.Id.soundLabel);
            soundLabel.Click += (o, e) =>
            {
                Intent intent = new Intent(RingtoneManager.ActionRingtonePicker);
                intent.PutExtra(RingtoneManager.ExtraRingtoneTitle, true);
                intent.PutExtra(RingtoneManager.ExtraRingtoneShowSilent, false);
                intent.PutExtra(RingtoneManager.ExtraRingtoneShowDefault, true);

                Android.Net.Uri uri;
                if (!String.IsNullOrEmpty(this.ViewModel.RingUri))
                {
                    uri = Android.Net.Uri.Parse(this.ViewModel.RingUri);
                }
                else
                {
                    uri = RingtoneManager.GetDefaultUri(RingtoneType.Alarm);
                }

                intent.PutExtra(RingtoneManager.ExtraRingtoneExistingUri, uri);

                StartActivityForResult(Intent.CreateChooser(intent, "Wybierz dzwonek"), 0);

                //Android.Net.Uri ring = (Android.Net.Uri)intent.GetParcelableExtra(RingtoneManager.ExtraRingtonePickedUri);
            };

            this.snooze        = this.FindViewById <TextView>(Resource.Id.snooze);
            this.snooze.Click += (sender, e) => { this.InputClicked(sender, e, this.ViewModel.SetSnooze, this.ViewModel.SnoozeMinutes, "Drzemka"); };

            this.window        = this.FindViewById <TextView>(Resource.Id.window);
            this.window.Click += (sender, e) => { this.InputClicked(sender, e, this.ViewModel.SetWindow, this.ViewModel.WindowHours, "Okienko 'najbliższe"); };

            SetBinding();
        }
        private void Process(HttpListenerContext context)
        {
            context.Response.AddHeader("Access-Control-Allow-Origin", "*");
            context.Response.AddHeader("Access-Control-Allow-Credentials", "true");
            context.Response.AddHeader("Access-Control-Allow-Methods", "*");
            context.Response.AddHeader("Access-Control-Allow-Headers", "*");
            if (context.Request.Url.ToString().Contains("&&querry&&"))
            {
                if (context.Request.Url.ToString().Contains("meconecte"))
                {
                    context.Response.StatusCode = (int)HttpStatusCode.OK;
                    context.Response.Close();
#pragma warning disable CS0618 // El tipo o el miembro están obsoletos
                    Notification.Builder nBuilder = new Notification.Builder(conteto);
#pragma warning restore CS0618 // El tipo o el miembro están obsoletos
                    nBuilder.SetContentTitle("Nuevo dispositivo conectado");
                    nBuilder.SetContentText("Un nuevo dispositivo está stremeando su media");
#pragma warning disable CS0618 // El tipo o el miembro están obsoletos
                    nBuilder.SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification));
#pragma warning restore CS0618 // El tipo o el miembro están obsoletos


                    nBuilder.SetSmallIcon(Resource.Drawable.antena);

                    Notification        notification        = nBuilder.Build();
                    NotificationManager notificationManager =
                        (NotificationManager)conteto.GetSystemService(Context.NotificationService);
                    notificationManager.Notify(5126768, notification);
                }
            }
            //////////////cuando son archivos
            else
            {
                bool   esindice = false;
                string filename = context.Request.Url.AbsolutePath;
                Console.WriteLine(filename);
                filename = filename.Substring(1);
                filename = System.Net.WebUtility.UrlDecode(filename);

                if (string.IsNullOrEmpty(filename))
                {
                    foreach (string indexFile in _indexFiles)
                    {
                        if (File.Exists(Path.Combine(_rootDirectory + "/.gr3cache", indexFile)))
                        {
                            filename = indexFile;
                            esindice = true;
                            break;
                        }
                    }
                }
                var nomesinpath = filename;
                if (!esindice)
                {
                    if (!filename.Contains(".mp3") && !filename.Contains(".mp4"))
                    {
                        filename = Path.Combine(_rootDirectory, filename);
                    }
                }
                else
                {
                    filename = Path.Combine(_rootDirectory + "/.gr3cache", filename);
                }
                if (File.Exists(filename))
                {
                    context.Response.StatusCode = (int)HttpStatusCode.OK;
                    //Adding permanent http response headers

                    string mime;
                    string mimo = "";
                    if (filename.EndsWith("mp3"))
                    {
                        mimo = "audio/*";
                    }
                    else
                    if (filename.EndsWith("mp4"))
                    {
                        mimo = "video/mp4";
                    }
                    if (!filename.Contains("downloaded.gr3d"))
                    {
                        using (var stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            context.Response.ContentType     = _mimeTypeMappings.TryGetValue(Path.GetExtension(filename), out mime) ? mime : mimo;
                            context.Response.ContentLength64 = stream.Length;
                            context.Response.AddHeader("Accept-Ranges", "bytes");
                            context.Response.AddHeader("Date", DateTime.Now.ToString("r"));
                            context.Response.AddHeader("Last-Modified", System.IO.File.GetLastWriteTime(filename).ToString("r"));
                            context.Response.AddHeader("Content-Range", string.Format("bytes {0}-{1}/{2}", 0, Convert.ToInt32(stream.Length) - 1, Convert.ToInt32(stream.Length)));
                            context.Response.ContentLength64 = stream.Length;
                            stream.CopyTo(context.Response.OutputStream);
                            stream.Flush();
                        }
                    }
                    else
                    {
                        refreshregistry();
                        byte[] bytesitosdestring;
                        if (filename.EndsWith("2"))
                        {
                            bytesitosdestring = System.Text.Encoding.UTF8.GetBytes(verifiedmp4);
                        }
                        else
                        {
                            bytesitosdestring = System.Text.Encoding.UTF8.GetBytes(verifiedmp3);
                        }

                        using (MemoryStream streamm = new MemoryStream(bytesitosdestring, 0, bytesitosdestring.Length))
                        {
                            context.Response.ContentType     = _mimeTypeMappings.TryGetValue(filename.Split('.')[1], out mime) ? mime : mimo;
                            context.Response.ContentLength64 = streamm.Length;
                            context.Response.SendChunked     = true;
                            context.Response.AddHeader("Date", DateTime.Now.ToString("r"));
                            context.Response.AddHeader("Last-Modified", System.IO.File.GetLastWriteTime(filename).ToString("r"));

                            streamm.CopyTo(context.Response.OutputStream);
                            streamm.Flush();
                        }
                        MultiHelper.ExecuteGarbageCollection();
                    }

                    context.Response.OutputStream.Flush();
                    context.Response.OutputStream.Close();
                    context.Response.Close();
                }
                else
                {
                    context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                    context.Response.Close();
                }
            }
        }
        public override void OnReceive(Context context, Intent intent)//הפעולה מעפילה את הברוקדקאסט בשביל שישלח התראה בעת קבלת שיחה
        {
            // ensure there is information
            if (intent.Extras != null)
            {
                // מקבל את מצב השיחה
                string state = intent.GetStringExtra(TelephonyManager.ExtraState);

                // check the current state בדיקה של המצב
                if (state == TelephonyManager.ExtraStateRinging)
                {
                    // read the incoming call telephone number... פרטי המתקשר
                    string chanel_id   = "chanel_id";
                    string chanel_name = "chanel-name";
                    if (Build.VERSION.SdkInt >= BuildVersionCodes.O)

                    {
                        NotificationChannel notificationChannel = new NotificationChannel(chanel_id, chanel_name, NotificationImportance.Default);

                        //מפעיל את האור בהתרעה
                        notificationChannel.EnableLights(true);

                        //מפעיל את הרטט
                        notificationChannel.EnableVibration(true);

                        //צבע ההתרעה
                        notificationChannel.LightColor = Color.White;

                        // קצב הרטט
                        // with the format {delay,play,sleep,play,sleep...}פורמט הרטט
                        notificationChannel.SetVibrationPattern(new long[] { 500, 500, 500, 500, 500 });

                        //מגדיר אם הודעות מהערוץ הזה צריכות להיות גלויות על מסך הנעילה ובמקרה הזה כן
                        notificationChannel.LockscreenVisibility = NotificationVisibility.Public;

                        NotificationManager manager = (NotificationManager)context.GetSystemService(Context.NotificationService);
                        manager.CreateNotificationChannel(notificationChannel);
                    }


                    string telephone = intent.GetStringExtra(TelephonyManager.ExtraIncomingNumber);
                    Toast.MakeText(Android.App.Application.Context, telephone, ToastLength.Short).Show();//יוצר טוסט
                    // בדוק את הטלפון מחדש
                    if (string.IsNullOrEmpty(telephone))
                    {
                        telephone = string.Empty;
                    }
                    Notification.Builder builder = new Notification.Builder(context, chanel_id);//יצירת ההתראה ופרטיה
                    builder.SetContentTitle(telephone);
                    builder.SetContentText("you got an incoming phone call from" + telephone);
                    builder.SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification));


                    builder.SetSmallIcon(Android.Resource.Drawable.StarOn);
                    Notification              notification              = builder.Build(); //בנייתו
                    const int                 not_id                    = 101;             //האידי
                    NotificationManager       notificationManager       = (NotificationManager)context.GetSystemService(Context.NotificationService);
                    NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.From(context);

                    notificationManager.Notify(not_id, notification);//הנוטיפרישין עצמו
                }
                else if (state == TelephonyManager.ExtraStateOffhook)
                {
                    // incoming call answer
                    Toast.MakeText(Android.App.Application.Context, "you answerd the pohne", ToastLength.Short).Show();
                }
                else if (state == TelephonyManager.ExtraStateIdle)//השיחה הסתיימה
                {
                    Toast.MakeText(Android.App.Application.Context, "call as ended continue to play", ToastLength.Long).Show();
                }
            }
        }
Example #7
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;
            }
        }
        public virtual void OnReceived(IDictionary <string, object> parameters)
        {
            System.Diagnostics.Debug.WriteLine($"{DomainTag} - OnReceived");

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

            Context context = Application.Context;

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

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

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

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

            if (parameters.TryGetValue(NumberKey, out var num))
            {
                try
                {
                    notificationNumber = Convert.ToInt32(num);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"Failed to convert {num} to an integer {ex}");
                }
            }

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


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

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

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

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

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


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

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

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

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

            var extras = new Bundle();

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

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

            if (PushNotificationManager.NotificationActivityFlags != null)
            {
                resultIntent.SetFlags(PushNotificationManager.NotificationActivityFlags.Value);
            }
            var requestCode   = new Java.Util.Random().NextInt();
            var pendingIntent = PendingIntent.GetActivity(context, requestCode, resultIntent, PendingIntentFlags.UpdateCurrent);

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

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

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

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

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

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

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

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

            notificationBuilder.SetDeleteIntent(pendingDeleteIntent);

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

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

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

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

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

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

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

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

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

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

            var category = string.Empty;

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

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

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

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

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

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

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

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

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

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

            OnBuildNotification(notificationBuilder, parameters);

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

            notificationManager.Notify(tag, notifyId, notificationBuilder.Build());
        }
        public override void OnReceive(Context context, Intent intent)
        {
            var message = intent.GetStringExtra("message");
            var title   = intent.GetStringExtra("title");
            var id      = intent.GetIntExtra("id", 0);

            Bitmap largeIcon = largeIcon = BitmapFactory.DecodeResource(context.Resources, Resource.Drawable.icon);

            string channelId   = "zdrowieplus-111";
            string channelName = "ZdrowiePlus";

            // When user click notification, start an activity
            Intent notifyIntent = new Intent(context, typeof(MainActivity));

            if (title == "Pomiar")
            {
                notifyIntent.PutExtra("notification", "measurement");
                int type = intent.GetIntExtra("type", 0);
                notifyIntent.PutExtra("type", type);

                largeIcon = BitmapFactory.DecodeResource(context.Resources, Resource.Drawable.pulsometer_icon);
            }
            if (title == "Wizyta")
            {
                notifyIntent.PutExtra("notification", "visit");

                largeIcon = BitmapFactory.DecodeResource(context.Resources, Resource.Drawable.doctor_icon);
            }
            if (title == "Leki")
            {
                notifyIntent.PutExtra("notification", "medicine");

                largeIcon = BitmapFactory.DecodeResource(context.Resources, Resource.Drawable.medical_pill);
            }
            notifyIntent.PutExtra("id", id);

            // Set the activity to start in a new, empty task
            notifyIntent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop);
            PendingIntent contentIntent = PendingIntent.GetActivity(context, id, notifyIntent, PendingIntentFlags.UpdateCurrent);

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

            // Check if android API is >= 26 (Oreo 8.0)
            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                // Creating notification channel
                var channel = new NotificationChannel(channelId, channelName, NotificationImportance.High)
                {
                    Description = "ZdrowiePlus"
                };

                notificationManager.CreateNotificationChannel(channel);
            }

            // Instantiate the builder and set notification elements:
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId)
                                                 .SetPriority(2) //NotificationPriority.Max = 2, .Min = -2
                                                 .SetContentTitle(title)
                                                 .SetContentText(message)
                                                 .SetColor(Android.Graphics.Color.Blue)
                                                 .SetContentIntent(contentIntent)
                                                 .SetCategory(NotificationCompat.CategoryReminder)
                                                 .SetAutoCancel(true)
                                                 .SetDefaults((int)NotificationDefaults.Sound | (int)NotificationDefaults.Vibrate)
                                                 .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Alarm))
                                                 .SetSmallIcon(Resource.Drawable.round_schedule_24)
                                                 .SetLargeIcon(largeIcon)
                                                 .SetVisibility((int)NotificationVisibility.Secret);

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

            // Publish the notification:
            notificationManager.Notify(id, notification);
        }
Example #10
0
        void SendNotification(RemoteMessage messageBody)
        {
            var intent = new Intent(this, typeof(MainActivity));

            intent.AddFlags(ActivityFlags.ClearTop);
            var pendingIntent       = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
            var notificationBuilder = new Notification.Builder(this).SetSmallIcon(Resource.Drawable.icono).SetContentTitle(messageBody.GetNotification().Title).SetContentText(messageBody.GetNotification().Body).SetAutoCancel(true).SetContentIntent(pendingIntent).SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification)).SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 }).SetLights(Color.Red, 3000, 3000);
            var notificationManager = NotificationManager.FromContext(this);

            notificationManager.Notify(0, notificationBuilder.Build());
        }
        public static void Initialize(Context context, bool resetToken, bool createDefaultNotificationChannel = true, bool autoRegistration = true)
        {
            CrossFirebasePushNotification.Current.NotificationHandler = CrossFirebasePushNotification.Current.NotificationHandler ?? new DefaultPushNotificationHandler();
            FirebaseMessaging.Instance.AutoInitEnabled = autoRegistration;
            if (autoRegistration)
            {
                ThreadPool.QueueUserWorkItem(state =>
                {
                    var packageName = Application.Context.PackageManager.GetPackageInfo(Application.Context.PackageName, PackageInfoFlags.MetaData).PackageName;
                    var versionCode = Application.Context.PackageManager.GetPackageInfo(Application.Context.PackageName, PackageInfoFlags.MetaData).VersionCode;
                    var versionName = Application.Context.PackageManager.GetPackageInfo(Application.Context.PackageName, PackageInfoFlags.MetaData).VersionName;
                    var prefs       = Android.App.Application.Context.GetSharedPreferences(FirebasePushNotificationManager.KeyGroupName, FileCreationMode.Private);

                    try
                    {
                        var storedVersionName = prefs.GetString(FirebasePushNotificationManager.AppVersionNameKey, string.Empty);
                        var storedVersionCode = prefs.GetString(FirebasePushNotificationManager.AppVersionCodeKey, string.Empty);
                        var storedPackageName = prefs.GetString(FirebasePushNotificationManager.AppVersionPackageNameKey, string.Empty);


                        if (resetToken || (!string.IsNullOrEmpty(storedPackageName) && (!storedPackageName.Equals(packageName, StringComparison.CurrentCultureIgnoreCase) || !storedVersionName.Equals(versionName, StringComparison.CurrentCultureIgnoreCase) || !storedVersionCode.Equals($"{versionCode}", StringComparison.CurrentCultureIgnoreCase))))
                        {
                            CleanUp(false);
                        }
                    }
                    catch (Exception ex)
                    {
                        _onNotificationError?.Invoke(CrossFirebasePushNotification.Current, new FirebasePushNotificationErrorEventArgs(FirebasePushNotificationErrorType.UnregistrationFailed, ex.ToString()));
                    }
                    finally
                    {
                        var editor = prefs.Edit();
                        editor.PutString(FirebasePushNotificationManager.AppVersionNameKey, $"{versionName}");
                        editor.PutString(FirebasePushNotificationManager.AppVersionCodeKey, $"{versionCode}");
                        editor.PutString(FirebasePushNotificationManager.AppVersionPackageNameKey, $"{packageName}");
                        editor.Commit();
                    }


                    CrossFirebasePushNotification.Current.RegisterForPushNotifications();
                });
            }


            if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O && createDefaultNotificationChannel)
            {
                // Create channel to show notifications.
                var channelId           = DefaultNotificationChannelId;
                var channelName         = DefaultNotificationChannelName;
                var notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService);

                Android.Net.Uri defaultSoundUri = SoundUri != null ? SoundUri : RingtoneManager.GetDefaultUri(RingtoneType.Notification);
                AudioAttributes attributes      = new AudioAttributes.Builder()
                                                  .SetUsage(AudioUsageKind.Notification)
                                                  .SetContentType(AudioContentType.Sonification)
                                                  .SetLegacyStreamType(Stream.Notification)
                                                  .Build();

                NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, DefaultNotificationChannelImportance);
                notificationChannel.EnableLights(true);
                notificationChannel.SetSound(defaultSoundUri, attributes);

                notificationManager.CreateNotificationChannel(notificationChannel);
            }

            System.Diagnostics.Debug.WriteLine(CrossFirebasePushNotification.Current.Token);
        }
Example #12
0
        private void BuildNotifation(Context context, string contentText, string title = "Panama", bool isCritial = false)
        {
            var pendingIntent = PendingIntent.GetActivity(context, 0, new Intent(context, typeof(MainActivity)), 0);
            var notification  = new Notification.Builder(context)
                                .SetContentIntent(pendingIntent)
                                .SetSmallIcon(Resource.Drawable.icon)
                                .SetContentTitle(title)
                                .SetStyle(new Notification.BigTextStyle().BigText(contentText))
                                .SetContentText(contentText)
                                .SetPriority(isCritial ? (int)NotificationPriority.Max : (int)NotificationPriority.Default)
                                .SetVisibility(NotificationVisibility.Public)
                                .SetCategory(Notification.CategoryAlarm)
                                .SetDefaults(NotificationDefaults.Vibrate)
                                .SetSound(isCritial ? RingtoneManager.GetDefaultUri(RingtoneType.Alarm) : RingtoneManager.GetDefaultUri(RingtoneType.Notification))
                                .Build();
            var notificationManager = context.GetSystemService(Context.NotificationService) as NotificationManager;

            // Publish the notification:
            notificationManager.Notify(notificationId++, notification);
        }
        private async Task SendNotification(string messageBody, IDictionary <string, string> data)
        {
            var intent = new Intent(this, typeof(MainActivity));

            //intent.AddFlags(ActivityFlags.ReorderToFront | ActivityFlags.SingleTop);
            intent.AddFlags(ActivityFlags.ClearTop);
            foreach (string key in data.Keys)
            {
                intent.PutExtra(key, data[key]);
            }

            var title = "Alarmo! Alarmo!";

            if (data.ContainsKey("title"))
            {
                var titleOverride = data["title"];
                if (!string.IsNullOrWhiteSpace(titleOverride))
                {
                    title = titleOverride;
                }
            }

            var message = "Unrecognized Person Detected!";

            if (data.ContainsKey("message"))
            {
                var messageOverride = data["message"];
                if (!string.IsNullOrWhiteSpace(messageOverride))
                {
                    message = messageOverride;
                }
            }

            var uri                 = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
            var pendingIntent       = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
            var notificationBuilder = new Notification.Builder(this)
                                      .SetSmallIcon(Resource.Drawable.ic_logo)
                                      .SetContentTitle(title)
                                      .SetContentText(message)
                                      .SetAutoCancel(true)
                                      .SetContentIntent(pendingIntent)
                                      .SetDefaults(NotificationDefaults.Sound);

            var imageReference = data.ContainsKey("imageReference") ? data["imageReference"] : null;

            if (!string.IsNullOrWhiteSpace(imageReference))
            {
                try
                {
                    imageReference = imageReference.WithToken();
                    var notificationStyle = new Notification.BigPictureStyle();
                    notificationStyle.SetSummaryText(message);
                    var client      = new HttpClient();
                    var imageStream = await client.GetStreamAsync(imageReference);

                    var detectionImage = global::Android.Graphics.BitmapFactory.DecodeStream(imageStream);
                    notificationStyle.BigPicture(detectionImage);
                    notificationStyle.BigLargeIcon((global::Android.Graphics.Bitmap)null);
                    notificationBuilder.SetLargeIcon(detectionImage);
                    notificationBuilder.SetStyle(notificationStyle);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex);
                }
            }

            var notificationManager = NotificationManager.FromContext(this);

            if (global::Android.OS.Build.VERSION.SdkInt >= global::Android.OS.BuildVersionCodes.O)
            {
                var channelId = "DetectionsChannel_01";
                var channel   = new NotificationChannel(channelId, "Detections Channel", NotificationImportance.High);
                notificationManager.CreateNotificationChannel(channel);
                notificationBuilder.SetChannelId(channelId);
            }

            var notification = notificationBuilder.Build();

            notificationManager.Notify(0, notification);
        }
        private void SendNotification(string title, string body, string clickaction)
        {
            var intent = new Intent(this, typeof(MainActivity));

            if (!string.IsNullOrEmpty(clickaction))
            {
                //if we have a click action open corresponding activity
                intent = new Intent(clickaction);
            }

            intent.AddFlags(ActivityFlags.ClearTop);
            // intent.PutExtra("launchArguments", "stuff");

            var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);

            var defaultSoundUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification);

            var notificationBuilder =
                new NotificationCompat.Builder(this)
                .SetSmallIcon(Resource.Drawable.InpowerIcon85x85)
                .SetContentTitle(title)
                .SetContentText(body)

                .SetAutoCancel(true)
                .SetSound(defaultSoundUri)
                .SetContentIntent(pendingIntent)
                .SetGroup(title);
            var notificationManager = NotificationManager.FromContext(this);

            notificationManager.Notify(0, notificationBuilder.Build());

            var notificationBuilder2 =
                new NotificationCompat.Builder(this)
                .SetSmallIcon(Resource.Drawable.InpowerIcon85x85)
                .SetContentTitle(title)
                .SetContentText(body)

                .SetAutoCancel(true)
                .SetSound(defaultSoundUri)
                .SetContentIntent(pendingIntent)
                .SetGroup(title);
            var notificationManage2r = NotificationManager.FromContext(this);

            notificationManager.Notify(0, notificationBuilder.Build());

            Notification summaryNotification =
                new NotificationCompat.Builder(this)
                .SetContentTitle(title)
                .SetContentTitle("Two new messages")
                .SetSmallIcon(Resource.Drawable.InpowerIcon85x85)
                .SetStyle(new NotificationCompat.InboxStyle()
                          .AddLine(title)
                          .AddLine(body)
                          .SetBigContentTitle(body)
                          .SetSummaryText(body))
                .SetGroup(title)
                .SetGroupSummary(true)
                .Build();

            NotificationManagerCompat notificationManager3 = NotificationManagerCompat.From(this);

            notificationManager.Notify(1, summaryNotification);
            notificationManager.Notify(2, summaryNotification);
            notificationManager.Notify(1, summaryNotification);
        }
Example #15
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(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();
            }


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

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

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

                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 = typeof(Activity).IsAssignableFrom(PushNotificationManager.NotificationActivityType) ? new Intent(Application.Context, PushNotificationManager.NotificationActivityType) : context.PackageManager.GetLaunchIntentForPackage(context.PackageName);

            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 (PushNotificationManager.NotificationActivityFlags != null)
            {
                resultIntent.SetFlags(PushNotificationManager.NotificationActivityFlags.Value);
            }

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

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

            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(PushNotificationManager.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 (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 = typeof(Activity).IsAssignableFrom(PushNotificationManager.NotificationActivityType) ? new Intent(Application.Context, PushNotificationManager.NotificationActivityType) : context.PackageManager.GetLaunchIntentForPackage(context.PackageName);

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

                                    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());
        }
Example #16
0
        void CreateNotification(string title, string message, int notifyId, string tag, Bundle extras)
        {
            System.Diagnostics.Debug.WriteLine(string.Format("{0} - PushNotification - Message {1} : {2}", PushNotificationKey.DomainName, title, message));

            NotificationCompat.Builder builder = null;
            Context context = Android.App.Application.Context;

            if (CrossPushNotification.SoundUri == null)
            {
                CrossPushNotification.SoundUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
            }
            try
            {
                if (CrossPushNotification.IconResource == 0)
                {
                    CrossPushNotification.IconResource = context.ApplicationInfo.Icon;
                }
                else
                {
                    string name = context.Resources.GetResourceName(CrossPushNotification.IconResource);

                    if (name == null)
                    {
                        CrossPushNotification.IconResource = context.ApplicationInfo.Icon;
                    }
                }
            }
            catch (Android.Content.Res.Resources.NotFoundException ex)
            {
                CrossPushNotification.IconResource = context.ApplicationInfo.Icon;
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }


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

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

            if (extras != null)
            {
                resultIntent.PutExtras(extras);
            }

            // Create a PendingIntent; we're only using one PendingIntent (ID = 0):
            const int     pendingIntentId     = 0;
            PendingIntent resultPendingIntent = PendingIntent.GetActivity(context, pendingIntentId, resultIntent, PendingIntentFlags.OneShot);

            // Build the notification
            builder = new NotificationCompat.Builder(context)
                      .SetAutoCancel(true)                              // dismiss the notification from the notification area when the user clicks on it
                      .SetContentIntent(resultPendingIntent)            // start up this activity when the user clicks the intent.
                      .SetContentTitle(title)                           // Set the title
                      .SetSound(CrossPushNotification.SoundUri)
                      .SetSmallIcon(CrossPushNotification.IconResource) // This is the icon to display
                      .SetContentText(message);                         // the message to display.

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

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

            notificationManager.Notify(tag, notifyId, builder.Build());
        }
        /// <summary>
        /// Create local notification
        /// </summary>
        /// <param name="title"></param>
        /// <param name="message"></param>
        public void CreateNotification(string title, string message)
        {
            try
            {
                NotificationCompat.Builder builder = null;
                Context context = Android.App.Application.Context;

                if (CrossGeofence.SoundUri == null)
                {
                    CrossGeofence.SoundUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
                }
                try
                {
                    if (CrossGeofence.IconResource == 0)
                    {
                        CrossGeofence.IconResource = context.ApplicationInfo.Icon;
                    }
                    else
                    {
                        string name = context.Resources.GetResourceName(CrossGeofence.IconResource);

                        if (name == null)
                        {
                            CrossGeofence.IconResource = context.ApplicationInfo.Icon;
                        }
                    }
                }
                catch (Android.Content.Res.Resources.NotFoundException ex)
                {
                    CrossGeofence.IconResource = context.ApplicationInfo.Icon;
                    System.Diagnostics.Debug.WriteLine(ex.ToString());
                }

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

                // Create a PendingIntent; we're only using one PendingIntent (ID = 0):
                const int     pendingIntentId     = 0;
                PendingIntent resultPendingIntent = PendingIntent.GetActivity(context, pendingIntentId, resultIntent, PendingIntentFlags.OneShot);


                // Build the notification
                builder = new NotificationCompat.Builder(context)
                          .SetAutoCancel(true)                      // dismiss the notification from the notification area when the user clicks on it
                          .SetContentIntent(resultPendingIntent)    // start up this activity when the user clicks the intent.
                          .SetContentTitle(title)                   // Set the title
                          .SetSound(CrossGeofence.SoundUri)
                          .SetSmallIcon(CrossGeofence.IconResource) // This is the icon to display
                          .SetContentText(message);                 // the message to display.

                // Set the icon resource if we have one
                if (CrossGeofence.LargeIconResource != null)
                {
                    builder.SetLargeIcon(CrossGeofence.LargeIconResource);
                }

                // Set the color if we have one
                if (CrossGeofence.Color != 0)
                {
                    builder.SetColor(CrossGeofence.Color);
                }


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

                if (NotificationId >= NotificationMaxId)
                {
                    NotificationId = 0;
                }

                notificationManager.Notify(NotificationId++, builder.Build());
            }
            catch (Java.Lang.Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(string.Format("{0} - {1}", CrossGeofence.Id, ex.ToString()));
            }
            catch (System.Exception ex1)
            {
                System.Diagnostics.Debug.WriteLine(string.Format("{0} - {1}", CrossGeofence.Id, ex1.ToString()));
            }
        }
        public override Task Send(Notification notification)
        {
            if (notification.Id == null)
            {
                Services.Repository.CurrentScheduleId++;
                notification.Id = Services.Repository.CurrentScheduleId;
            }

            if (notification.IsScheduled)
            {
                var triggerMs = this.GetEpochMills(notification.SendTime);
                var pending   = notification.ToPendingIntent(notification.Id.Value);

                this.alarmManager.Set(
                    AlarmType.RtcWakeup,
                    Convert.ToInt64(triggerMs),
                    pending
                    );
                Services.Repository.Insert(notification);
            }
            else
            {
                var launchIntent = Application.Context.PackageManager.GetLaunchIntentForPackage(Application.Context.PackageName);
                launchIntent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);
                foreach (var pair in notification.Metadata)
                {
                    launchIntent.PutExtra(pair.Key, pair.Value);
                }

                var builder = new Android.App.Notification.Builder(Application.Context)
                              .SetAutoCancel(true)
                              .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification))
                              .SetContentTitle(notification.Title)
                              .SetContentText(notification.Message)
                              .SetSmallIcon(AppIconResourceId)
                              .SetPriority(priority.HasValue ? priority.Value : NotificationCompat.PriorityMax)
                              .SetContentIntent(TaskStackBuilder
                                                .Create(Application.Context)
                                                .AddNextIntent(launchIntent)
                                                .GetPendingIntent(notification.Id.Value, PendingIntentFlags.OneShot)
                                                );

                if (notification.Vibrate)
                {
                    builder.SetVibrate(new long[] { 500, 500 });
                }

                if (notification.Sound != null)
                {
                    if (!notification.Sound.Contains("://"))
                    {
                        notification.Sound = $"{ContentResolver.SchemeAndroidResource}://{Application.Context.PackageName}/raw/{notification.Sound}";
                    }
                    var uri = Android.Net.Uri.Parse(notification.Sound);
                    builder.SetSound(uri);
                }
                var not = builder.Build();
                NotificationManagerCompat
                .From(Application.Context)
                .Notify(notification.Id.Value, not);
            }
            return(Task.CompletedTask);
        }