public void Notify(Intent intent)
        {
            var    rand              = new Random();
            var    randomNum         = rand.Next();
            Bundle valuesForActivity = new Bundle();

            valuesForActivity.PutInt("topicId", randomNum);

            Global.SetNotifTopic(intent.Extras.GetString("push_type"));
            Global.SetListTopic(randomNum, intent.Extras.GetString("push_type"));


            Intent resultIntent = new Intent(this, typeof(MainActivity));

            resultIntent.PutExtras(valuesForActivity);

            Android.Support.V4.App.TaskStackBuilder stackBuilder = Android.Support.V4.App.TaskStackBuilder.Create(this);
            stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(MainActivity)));
            stackBuilder.AddNextIntent(resultIntent);

            // Create the PendingIntent with the back stack:
            PendingIntent resultPendingIntent =
                stackBuilder.GetPendingIntent(0, (int)PendingIntentFlags.UpdateCurrent);

            var fullmessage = intent.Extras.GetString("message") + "\n" + intent.Extras.GetString("article_data");
            var imageBitmap = GetImageBitmapFromUrl(intent.Extras.GetString("image_url"));

            NotificationCompat.BigPictureStyle picstyle = new NotificationCompat.BigPictureStyle();
            picstyle.BigPicture(imageBitmap);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                                                 .SetAutoCancel(true)
                                                 .SetContentIntent(resultPendingIntent)
                                                 .SetContentTitle(intent.Extras.GetString("title"))
                                                 .SetNumber(Global.GetNotifCount())
                                                 .SetStyle(picstyle)
                                                 .SetSmallIcon(Resource.Drawable.UmbrellaArmyFavicon)
                                                 .SetContentText(String.Format(fullmessage));

            // Finally, publish the notification:
            NotificationManager notificationManager =
                (NotificationManager)GetSystemService(Context.NotificationService);

            notificationManager.Notify(ButtonClickNotificationId, builder.Build());

            if (Global.GetNotifTopic() != "general" || Global.GetNotifTopic() != "general_android")
            {
                var message = new StartLongRunningTaskMessage();
                MessagingCenter.Send(message, "StartLongRunningTaskMessage");
            }
        }
示例#2
0
        private void SendNotification(string title, string body, int id)
        {
            Intent intent = new Intent(this, typeof(NotificationActivity));

            intent.PutExtra("main_message", "This message is sent from MainActivity.cs!");
            PendingIntent pendingIntent =
                PendingIntent.GetActivity(this, 1, intent, PendingIntentFlags.OneShot);

            NotificationCompat.BigPictureStyle bigImage = new NotificationCompat.BigPictureStyle();
            bigImage.BigPicture(BitmapFactory.DecodeResource(Resources, Resource.Drawable.Xamarin));
            //NotificationCompat = class which defines all the metadata of the
            //                      notifications to be created -> styles, creation of object builder

            //NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
            //bigText.BigText("This is a super super super super super super super super\n" +
            //    "super super super super super super super super large text.....");
            //bigText.SetSummaryText("a super giant TEXT");
            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
            inboxStyle.SetSummaryText("An image from Xamarin.Android");
            //bigPicture.BigLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.ic_launcher_round));
            inboxStyle.SetBigContentTitle("This is the Big Content Title");
            inboxStyle.SetSummaryText("This is the summary text");
            inboxStyle.AddLine("Line 1");
            inboxStyle.AddLine("Line 2");
            inboxStyle.AddLine("Line 3");
            inboxStyle.AddLine("Line 4");
            inboxStyle.AddLine("Line 5");
            NotificationCompat.Builder builder =
                new NotificationCompat.Builder(this, CHANNEL_ID)
                .SetStyle(inboxStyle)
                .SetCategory(Notification.CategoryMessage)
                .SetContentIntent(pendingIntent)
                .SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.ic_launcher_round))
                .SetContentTitle(title)
                .SetContentText(body)
                .SetSmallIcon(Resource.Drawable.ic_launcher_round)
                .SetDefaults((int)(NotificationDefaults.Sound | NotificationDefaults.Vibrate))
                .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Alarm));

            Notification notificationObject = builder.Build();

            // notificationObject.Defaults |= NotificationDefaults.All;
            // set more notification metadata even when notification object is created

            var notificationManager = (NotificationManager)GetSystemService(NotificationService);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            var serializedRequest = JsonSerializer.Serialize(request);

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

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

            builder.SetContentIntent(pendingIntent);

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

            var notification = builder.Build();

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

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

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

            AddPreferencesNotificationId(PreferencesDeliveredIdListKey, request.NotificationId);

            return(true);
        }
示例#4
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;
            }

            int notifyId        = 0;
            int summaryNotifyId = 786;

            string title   = context.ApplicationInfo.LoadLabel(context.PackageManager);
            var    message = string.Empty;
            var    tag     = string.Empty;
            var    image   = string.Empty;

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

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

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

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

            if (parameters.TryGetValue(ImageKey, out object imageContent))
            {
                image = imageContent.ToString();
            }

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

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

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

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

            Bundle extras = new Bundle();

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

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

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

            var notificationStr = appPreferences.GetNotifications();
            List <NotificationModel> notificationList = JsonConvert.DeserializeObject <List <NotificationModel> >(notificationStr);

            notificationList.Add(new NotificationModel {
                NotifiyId = notifyId,
                Title     = title,
                Message   = message
            });
            appPreferences.SaveNotification(notificationList);

            var pendingIntent = PendingIntent.GetActivity(context, requestCode, resultIntent, PendingIntentFlags.UpdateCurrent);
            var deleteIntent  = new Intent(context, typeof(PushNotificationDeletedReceiver));

            deleteIntent.PutExtras(extras);

            var pendingDeleteIntent = PendingIntent.GetBroadcast(context, requestCode, deleteIntent, PendingIntentFlags.CancelCurrent);

            var chanId = FirebasePushNotificationManager.DefaultNotificationChannelId;

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

            // Image Notification
            if (!string.IsNullOrEmpty(image))
            {
                URL    url    = new URL(image);
                Bitmap bitmap = BitmapFactory.DecodeStream(url.OpenConnection().InputStream);

                NotificationCompat.BigPictureStyle notifyImageStyle = new NotificationCompat.BigPictureStyle();
                notifyImageStyle.BigPicture(bitmap);
                notifyImageStyle.BigLargeIcon(bitmap);

                var notification = new NotificationCompat.Builder(context, chanId)
                                   .SetSmallIcon(FirebasePushNotificationManager.IconResource)
                                   .SetContentTitle(title)
                                   .SetContentText(message)
                                   .SetStyle(notifyImageStyle)
                                   .SetAutoCancel(true)
                                   .SetDefaults((int)NotificationDefaults.Lights)
                                   .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification))
                                   .SetContentIntent(pendingIntent)
                                   .SetDeleteIntent(pendingDeleteIntent);

                SetNotificationPriority(notification, parameters);
                ResolveLocalizedParameters(notification, parameters);
                SetNotificationAction(notification, parameters, extras);
                OnBuildNotification(notification, parameters);

                if (CrossFirebaseEssentials.Notifications.CanShowNotification)
                {
                    notificationManager.Notify(104, notification.Build());
                }
                return;
            }

            // Group Notification
            string groupKey  = string.Format("{0}{1}", context.ApplicationInfo.LoadLabel(context.PackageManager), "Notification");
            var    groupList = notificationList.GroupBy(x => x.Title).ToList();

            for (int i = 0; i < groupList.Count; i++)
            {
                var lstNotification = groupList[i].ToList();
                NotificationCompat.InboxStyle notifyInboxStyle = new NotificationCompat.InboxStyle();

                foreach (var item in lstNotification)
                {
                    notifyInboxStyle.AddLine(item.Message);
                }

                var notification = new NotificationCompat.Builder(context, chanId)
                                   .SetSmallIcon(FirebasePushNotificationManager.IconResource)
                                   .SetContentTitle(groupList[i].Key)
                                   .SetContentText(lstNotification.LastOrDefault().Message)
                                   .SetStyle(notifyInboxStyle)
                                   .SetAutoCancel(true)
                                   .SetGroup(groupKey)
                                   .SetDefaults((int)NotificationDefaults.Lights)
                                   .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification))
                                   .SetContentIntent(pendingIntent)
                                   .SetDeleteIntent(pendingDeleteIntent);

                SetNotificationPriority(notification, parameters);
                ResolveLocalizedParameters(notification, parameters);
                SetNotificationAction(notification, parameters, extras);
                OnBuildNotification(notification, parameters);

                if (CrossFirebaseEssentials.Notifications.CanShowNotification)
                {
                    notificationManager.Notify(i, notification.Build());
                }
            }

            NotificationCompat.InboxStyle summaryInboxStyle = new NotificationCompat.InboxStyle()
                                                              .SetSummaryText(string.Format("{0} new messages", groupList.Count))
                                                              .SetBigContentTitle(context.ApplicationInfo.LoadLabel(context.PackageManager));

            foreach (var item in groupList)
            {
                var lstNotification = item.ToList();
                summaryInboxStyle.AddLine(string.Format("{0} {1}", item.Key, lstNotification.LastOrDefault().Message));
            }

            var summaryNotification = new NotificationCompat.Builder(context, chanId)
                                      .SetSmallIcon(FirebasePushNotificationManager.IconResource)
                                      .SetAutoCancel(true)
                                      .SetStyle(summaryInboxStyle)
                                      .SetGroup(groupKey)
                                      .SetGroupAlertBehavior(NotificationCompat.GroupAlertChildren)
                                      .SetGroupSummary(true)
                                      .SetDefaults((int)NotificationDefaults.Lights)
                                      .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification))
                                      .SetContentIntent(pendingIntent)
                                      .SetDeleteIntent(pendingDeleteIntent);

            SetNotificationPriority(summaryNotification, parameters);
            ResolveLocalizedParameters(summaryNotification, parameters);
            SetNotificationAction(summaryNotification, parameters, extras);
            OnBuildNotification(summaryNotification, parameters);

            if (CrossFirebaseEssentials.Notifications.CanShowNotification)
            {
                notificationManager.Notify(summaryNotifyId, summaryNotification.Build());
            }
        }
示例#5
0
        public void UpdateNotification()
        {
            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                //create Notification Channel
                NotificationChannel channel = new NotificationChannel(MyConstants.CHANNEL_ID, MyConstants.CHANNEL_NAME, NotificationImportance.Default);
                channel.EnableVibration(true);
                channel.SetVibrationPattern(
                    new long[]
                    { 500, 500, 500, 500 });
                //set visibility on lockscreen
                channel.LockscreenVisibility = NotificationVisibility.Private;

                //create the channel
                NotificationManager manager = Android.App.Application.Context.GetSystemService(Context.NotificationService) as NotificationManager;
                manager.CreateNotificationChannel(channel);

                //set an action to tske the user to the active activity when user clicks on notification
                Intent intent = new Intent(Android.App.Application.Context, typeof(MainActivity));
                intent.SetAction(Intent.ActionMain);
                intent.AddCategory(Intent.CategoryLauncher);

                //create pendingIntent
                PendingIntent pendingIntent = PendingIntent.GetActivity(Android.App.Application.Context, 3, intent, 0);

                //build the notification
                var Notification = new NotificationCompat.Builder(Android.App.Application.Context, MyConstants.CHANNEL_ID);
                Notification.SetContentTitle("This is the updated Notification")
                .SetContentText("Testing updated Notification right now!")
                .SetSmallIcon(Resource.Drawable.ic_mr_button_grey)
                .SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis())
                .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Ringtone))
                .SetContentIntent(pendingIntent)
                .SetLargeIcon(BitmapFactory.DecodeResource(Android.App.Application.Context.Resources, Resource.Drawable.user));
                //create big text style notification in the expanded. This class does not support method chaining
                //you have to explitcitely use the NotificationBuilder object to call the BigTextStyle class
                NotificationCompat.BigTextStyle bigtext = new NotificationCompat.BigTextStyle();
                string gibberish = "This is the new big text style notification";
                gibberish += "/and we are just testing it";
                bigtext.BigText(gibberish);
                bigtext.SetSummaryText("This is just a summary");
                //push BigText into builder for the notification
                Notification.SetStyle(bigtext);
                //used to create image notification
                NotificationCompat.BigPictureStyle picturestyle = new NotificationCompat.BigPictureStyle();
                picturestyle.BigPicture(BitmapFactory.DecodeResource(Android.App.Application.Context.Resources, Resource.Drawable.bsplash));
                Notification.SetStyle(picturestyle);
                //Notification.SetPriority(NotificationPriority.High);

                //.SetLargeIcon(BitmapFactory.DecodeResource(GetDrawable(Resource.Drawable.badge), Resource.Drawable.badge);
                //.build the notification
                Notification notification = Notification.Build();
                //issue the Notification
                NotificationManager manager2 = NotificationManager.FromContext(Android.App.Application.Context);
                manager2.Notify(MyConstants.NOTIFICATION_ID, notification);
            }

            else
            {
                //set an action to tske the user to the active activity when user clicks on notification
                Intent intent = new Intent(Android.App.Application.Context, typeof(MainActivity));
                intent.AddCategory(Intent.CategoryLauncher);
                intent.SetAction(Intent.ActionMain);

                //create pendingIntent
                PendingIntent pendingIntent = PendingIntent.GetActivity(Android.App.Application.Context, 4, intent, 0);

                var notification = new NotificationCompat.Builder(Android.App.Application.Context, MyConstants.CHANNEL_ID_2);
                notification.SetContentTitle("This is the other updated notification")
                .SetContentText("This is the body of the other updated notification")
                .SetSmallIcon(Resource.Drawable.ic_audiotrack_dark)
                .SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis())
                .SetTimeoutAfter(6000)
                .SetContentIntent(pendingIntent)
                .SetLargeIcon(BitmapFactory.DecodeResource(Android.App.Application.Context.Resources, Resource.Drawable.user));
                //create big text style notification in the expanded. This class does not support method chaining
                //you have to explitcitly use the NotificationBuilder object to call the BigTextStyle class
                NotificationCompat.BigTextStyle bigtext = new NotificationCompat.BigTextStyle();
                string gibberish = "This is the new big text style notification";
                gibberish += "/and we are just testing it";
                bigtext.BigText(gibberish);
                bigtext.SetSummaryText("This is just a summary");
                //push BigText into builder for the notification
                notification.SetStyle(bigtext);
                //used to create image notification
                NotificationCompat.BigPictureStyle picturestyle = new NotificationCompat.BigPictureStyle();
                picturestyle.BigPicture(BitmapFactory.DecodeResource(Android.App.Application.Context.Resources, Resource.Drawable.bsplash));
                notification.SetStyle(picturestyle);

                Notification        Notiffy  = notification.Build();
                NotificationManager manager3 = NotificationManager.FromContext(Android.App.Application.Context);
                manager3.Notify(MyConstants.NOTIFICATION_ID_2, Notiffy);
            }
        }
示例#6
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)));

					// 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;
		}
示例#7
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);
        }
示例#8
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;
            }
        }