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;
		}
        /// <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);
        }
Beispiel #3
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);
        }