public void ShowNotification(Intent intent)
        {
            var id    = intent.GetIntExtra("id", 0);
            var title = intent.GetStringExtra("title");
            var body  = intent.GetStringExtra("message");

            var main_intent = new Intent(this, typeof(MainActivity));

            main_intent.PutExtra("type", "alarm");
            main_intent.PutExtra("id", id);

            var builder = new Notification.Builder(this);

            //builder.SetGroup("keep.grass");
            builder.SetTicker(title);
            builder.SetContentTitle(title);
            builder.SetContentText(body);
            builder.SetContentIntent
            (
                PendingIntent.GetActivity
                (
                    this,
                    id,
                    main_intent,
                    PendingIntentFlags.UpdateCurrent
                )
            );
            builder.SetSmallIcon(Resource.Drawable.icon);
            builder.SetLargeIcon(BitmapFactory.DecodeResource(this.Resources, Resource.Drawable.icon));
            builder.SetDefaults(NotificationDefaults.All);
            builder.SetAutoCancel(true);

            ((NotificationManager)this.GetSystemService(NotificationService))
            .Notify(id, builder.Build());
        }
        private void Button_Click(object sender, EventArgs e)
        {
            notyBuilder = new Notification.Builder(this);

            notyBuilder.SetContentTitle("عنوان پیام");
            notyBuilder.SetContentText("متن پیام در اینجا قرار میگیرد");
            notyBuilder.SetSmallIcon(Resource.Drawable.noty_small_icon);
            notyBuilder.SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.noty_large_icon));
            notyBuilder.SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis());
            notyBuilder.SetDefaults(NotificationDefaults.Sound | NotificationDefaults.Vibrate);
            notyBuilder.SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification));
            notyBuilder.SetAutoCancel(true);
            notyBuilder.SetPriority((int)NotificationPriority.High);

            if ((int)Android.OS.Build.VERSION.SdkInt >= 21)
            {
                notyBuilder.SetVisibility(NotificationVisibility.Public);
                notyBuilder.SetCategory(Notification.CategoryEmail);
            }



            #region BigTextStyle

            Notification.BigTextStyle textStyle = new Notification.BigTextStyle();
            string longTextMessage = "I went up one pair of stairs.";
            longTextMessage += " / Just like me. ";
            textStyle.BigText(longTextMessage);
            textStyle.SetSummaryText("The summary text goes here.");
            //notyBuilder.SetStyle(textStyle);

            #endregion

            #region InboxStyle

            var inboxStyle = new Notification.InboxStyle();
            inboxStyle.AddLine("Cheeta: Bananas on sale");
            inboxStyle.AddLine("George: Curious about your blog post");
            inboxStyle.AddLine("Nikko: Need a ride to Evolve?");
            inboxStyle.SetSummaryText("+2 more");

            notyBuilder.SetStyle(inboxStyle);

            #endregion

            #region imageStyle

            var imageStyle = new Notification.BigPictureStyle();
            imageStyle.BigPicture(BitmapFactory.DecodeResource(Resources, Resource.Drawable.facebook));
            imageStyle.SetSummaryText("+2 more");
            //notyBuilder.SetStyle(imageStyle);


            #endregion

            var notification = notyBuilder.Build();
            var notyManager  = GetSystemService(Context.NotificationService) as NotificationManager;
            notyManager.Notify(notyId, notification);
        }
        /*
         * Submit notification with a small icon on the very right
         */
        public void SendCollapsedNotification(DigitalCity.Model.Notification notification)
        {
            var title   = notification.title;
            var content = notification.content;
            var image   = notification.imagePath;
            var id      = notification.GetId();

            //create builder and assign image to the notification
            Notification.Builder builder = CreateNotificationBuilder(title, content);
            int imageID = (int)typeof(Resource.Drawable).GetField(image).GetRawConstantValue();

            builder.SetLargeIcon(BitmapFactory.DecodeResource(CrossCurrentActivity.Current.Activity.Resources, imageID));
            PublishNotification(builder, id);
        }
示例#4
0
        private void SetNotificationBar()
        {
            if (tracks.Count == 0)
            {
                return;
            }
            Intent playPause = new Intent("Pause");
            Intent previous  = new Intent("Previous");
            Intent next      = new Intent("Next");
            Intent loop      = new Intent("LoopBack");
            Intent details   = new Intent("Details");
            Intent cancel    = new Intent("Cancel");

            PendingIntent playPausePending = PendingIntent.GetBroadcast(this, 0, playPause, PendingIntentFlags.CancelCurrent);
            PendingIntent previousPending  = PendingIntent.GetBroadcast(this, 1, previous, PendingIntentFlags.CancelCurrent);
            PendingIntent nextPending      = PendingIntent.GetBroadcast(this, 2, next, PendingIntentFlags.CancelCurrent);
            PendingIntent cancelPending    = PendingIntent.GetBroadcast(this, 3, cancel, PendingIntentFlags.CancelCurrent);
            PendingIntent loopPending      = PendingIntent.GetBroadcast(this, 4, loop, PendingIntentFlags.CancelCurrent);
            PendingIntent OpenDetails      = PendingIntent.GetBroadcast(this, 10, details, PendingIntentFlags.CancelCurrent);
            string        artist           = Track_Finder.TrackFinder.GetArtistOfTrack(tracks[song].Path);

            using (Notification.Builder not = new Notification.Builder(this, "com.PapIndustries.PapMediaPlayerService"))
            {
                using (Notification.MediaStyle mediaStyle = new Notification.MediaStyle())
                {
                    not.SetSmallIcon(Resource.Drawable.Logo).SetContentTitle(tracks[song].Title).SetContentText(artist)
                    .SetOngoing(player.IsPlaying).SetStyle(mediaStyle.SetShowActionsInCompactView(0, 1, 2, 3, 4))
                    .AddAction(Resource.Drawable.Previous, "Previous", previousPending).SetContentIntent(OpenDetails)
                    .SetPriority((int)NotificationPriority.Max).SetCategory(Notification.CategoryService);
                    Bitmap icon = Track_Finder.TrackFinder.GetImageOfTrack(tracks[song].Path);
                    not.SetLargeIcon(icon ?? BitmapFactory.DecodeResource(Resources, Resource.Drawable.Note));

                    if (!player.IsPlaying)
                    {
                        not.AddAction(Resource.Drawable.Play, "Play", playPausePending);
                    }
                    else
                    {
                        not.AddAction(Resource.Drawable.Pause, "Pause", playPausePending);
                    }
                    not.AddAction(Resource.Drawable.Next, "Next", nextPending);
                    not.AddAction(manager.GetIcon(), manager.GetTitle(), loopPending);
                    not.AddAction(Resource.Drawable.ExitNotificationIcon, "Exit", cancelPending);
                    var notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);
                    notify = not.Build();
                    notificationManager.Notify(SERVICE_ID, notify);
                }
            }
        }
 void FetchBitmapFromURL(string bitmapUrl, Notification.Builder builder)
 {
     AlbumArtCache.Instance.Fetch(bitmapUrl, new AlbumArtCache.FetchListener()
     {
         OnFetched = (artUrl, bitmap, icon) => {
             if (metadata != null && metadata.Description != null &&
                 artUrl == metadata.Description.IconUri.ToString())
             {
                 LogHelper.Debug(Tag, "fetchBitmapFromURLAsync: set bitmap to ", artUrl);
                 builder.SetLargeIcon(bitmap);
                 notificationManager.Notify(NotificationId, builder.Build());
             }
         }
     });
 }
示例#6
0
        public static void BuildNotification(String songId)
        {
            MediaMetadataRetriever metadata = SongMetadata.GetMetadata(songId);

            string title   = metadata.ExtractMetadata(MetadataKey.Title);
            string content = metadata.ExtractMetadata(MetadataKey.Artist);

            if (title == null || content == null)
            {
                title   = "TubeLoad";
                content = AndroidSongsManager.Instance.GetSong(songId).Name.Replace(".mp3", "");
            }

            builder.SetSmallIcon(Resource.Drawable.icon);
            Drawable drawable = SongMetadata.GetSongPicture(songId);
            Bitmap   bitmap;

            if (drawable != null)
            {
                bitmap = ((BitmapDrawable)SongMetadata.GetSongPicture(songId)).Bitmap;
            }
            else
            {
                bitmap = BitmapFactory.DecodeResource(Application.Context.Resources, Resource.Drawable.default_song_image);
            }

            if (Android.OS.Build.VERSION.SdkInt > Android.OS.BuildVersionCodes.M)
            {
                RemoteViews notificationLayoutExpanded = new RemoteViews(Application.Context.PackageName, Resource.Layout.view_notification_actions);
                notificationLayoutExpanded.SetTextViewText(Resource.Id.notificationTitle, title);
                notificationLayoutExpanded.SetTextViewText(Resource.Id.notificationContent, content);
                notificationLayoutExpanded.SetImageViewBitmap(Resource.Id.songImg, bitmap);
                CreateNotificationMediaActions(notificationLayoutExpanded);
                builder.SetCustomBigContentView(notificationLayoutExpanded);
                builder.SetContentTitle(title);
            }
            else
            {
                builder.SetLargeIcon(bitmap);
                builder.SetContentTitle(title);
                builder.SetContentText(content);
            }

            songNotification = builder.Build();

            notificationManager.Notify(SONG_NOTIFICATION_ID, songNotification);
        }
示例#7
0
        void ShowNotification(bool custom)
        {
            Resources           res = Resources;
            NotificationManager notificationManager = (NotificationManager)GetSystemService(
                NotificationService);

            Notification.Builder builder = new Notification.Builder(this)
                                           .SetSmallIcon(Resource.Drawable.ic_stat_notify_example)
                                           .SetAutoCancel(true)
                                           .SetTicker(GetString(Resource.String.notification_text))
                                           .SetContentIntent(GetDialogPendingIntent("Tapped the notification entry."));

            if (custom)
            {
                // Sets a custom content view for the notification, including an image button.
                RemoteViews layout = new RemoteViews(PackageName, Resource.Layout.notification);
                layout.SetTextViewText(Resource.Id.notification_title, GetString(Resource.String.app_name));
                layout.SetOnClickPendingIntent(Resource.Id.notification_button,
                                               GetDialogPendingIntent("Tapped the 'dialog' button in the notification."));
                builder.SetContent(layout);

                // Notifications in Android 3.0 now have a standard mechanism for displaying large
                // bitmaps such as contact avatars. Here, we load an example image and resize it to the
                // appropriate size for large bitmaps in notifications.
                Bitmap largeIconTemp = BitmapFactory.DecodeResource(res,
                                                                    Resource.Drawable.notification_default_largeicon);
                Bitmap largeIcon = Bitmap.CreateScaledBitmap(
                    largeIconTemp,
                    res.GetDimensionPixelSize(Android.Resource.Dimension.NotificationLargeIconWidth),
                    res.GetDimensionPixelSize(Android.Resource.Dimension.NotificationLargeIconHeight),
                    false);
                largeIconTemp.Recycle();

                builder.SetLargeIcon(largeIcon);
            }
            else
            {
                builder
                .SetNumber(7)                  // An example number.
                .SetContentTitle(GetString(Resource.String.app_name))
                .SetContentText(GetString(Resource.String.notification_text));
            }

            notificationManager.Notify(NotificationDefault, builder.Notification);
        }
示例#8
0
        public void SendNotificatios(string body, string Header)
        {
            Notification.Builder builder = new Notification.Builder(this);
            builder.SetSmallIcon(Resource.Drawable.Icon);
            var intent = new Intent(this, typeof(MainActivity));

            intent.AddFlags(ActivityFlags.ClearTop);
            PendingIntent pendingIntent = PendingIntent.GetActivity(this, 0, intent, 0);

            builder.SetContentIntent(pendingIntent);
            builder.SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.Icon));
            builder.SetContentTitle(Header);
            builder.SetContentText(body);
            builder.SetDefaults(NotificationDefaults.Sound);
            builder.SetAutoCancel(true);
            NotificationManager notificationManager = (NotificationManager)GetSystemService(NotificationService);

            notificationManager.Notify(1, builder.Build());
        }
示例#9
0
        /*
         * Invoked when showNotificationButton is clicked.
         * Creates a new notification and sets metadata passed as arguments.
         */
        public Notification CreateNotification(Priority priority, Category category, Uri contactUri)
        {
            var builder = new Notification.Builder(Activity)
                          .SetContentTitle("Notification with other metadata")
                          .SetSmallIcon(Resource.Drawable.ic_launcher_notification)
                          .SetPriority((int)priority.priority)
                          .SetCategory(category.ToString())
                          .SetContentText(string.Format("Category {0}, Priority {1}", category.ToString(), priority.ToString()));

            if (contactUri != null)
            {
                builder.AddPerson(contactUri.ToString());
                Bitmap photoBitmap = LoadBitmapFromContactUri(contactUri);
                if (photoBitmap != null)
                {
                    builder.SetLargeIcon(photoBitmap);
                }
            }
            return(builder.Build());
        }
 public static void ShowNotification(Activity contexto, string titulo, string mensaje, string link, int codigo)
 {
     contexto.RunOnUiThread(() =>
     {
         #pragma warning disable CS0618 // El tipo o el miembro están obsoletos
         var nBuilder = new Notification.Builder(contexto);
         #pragma warning restore CS0618 // El tipo o el miembro están obsoletos
         nBuilder.SetLargeIcon(ImageHelper.GetImageBitmapFromUrl("http://i.ytimg.com/vi/" + link.Split('=')[1] + "/mqdefault.jpg"));
         nBuilder.SetContentTitle(titulo);
         nBuilder.SetContentText(mensaje);
         nBuilder.SetColor(Android.Graphics.Color.ParseColor("#ce2c2b"));
         nBuilder.SetSmallIcon(Resource.Drawable.list);
         #pragma warning disable CS0618 // El tipo o el miembro están obsoletos
         nBuilder.SetSound(Android.Media.RingtoneManager.GetDefaultUri(Android.Media.RingtoneType.Notification));
         #pragma warning restore CS0618 // El tipo o el miembro están obsoletos
         Notification notification = nBuilder.Build();
         NotificationManager notificationManager = (NotificationManager)contexto.GetSystemService(Context.NotificationService);
         notificationManager.Notify(5126768, notification);
     });
 }
        void SendNotification(string title, string body)
        {
            Body = body;
            var intent = new Intent(this, typeof(MainActivity));

            intent.PutExtra("title", title);
            intent.PutExtra("body", body);

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

            long[] pattern = { 500, 500, 500, 500, 500 };

            var notificationBuilder = new Notification.Builder(this)
                                      .SetSmallIcon(Resource.Drawable.ic_save)
                                      .SetContentTitle("Coin Rate")
                                      .SetContentText(body)
                                      .SetAutoCancel(true)
                                      .SetVibrate(pattern)
                                      .SetLights(Color.Blue, 1, 1)
                                      .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification))
                                      .SetContentIntent(pendingIntent);

            //.setContentTitle(URLDecoder.decode(getString(R.string.app_name), "UTF-8"))
            //.setContentText(URLDecoder.decode(message, "UTF-8"))

            notificationBuilder.SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.xamarin_logo));
            notificationBuilder.SetSubText("Tap to view");
            //notificationBuilder.SetNumber(2);
            //notificationBuilder.SetWhen
            //notificationBuilder.SetTicker("you received another value");

            var notificationManager = NotificationManager.FromContext(this);

            notificationManager.Notify(0, notificationBuilder.Build());
        }
        private void Btn_intent_Click(object sender, EventArgs e)
        {
            notyBuilder = new Notification.Builder(this);

            notyBuilder.SetContentTitle("عنوان پیام");
            notyBuilder.SetContentText("متن پیام در اینجا قرار میگیرد");
            notyBuilder.SetSmallIcon(Resource.Drawable.noty_small_icon);
            notyBuilder.SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.noty_large_icon));
            notyBuilder.SetAutoCancel(true);

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

            notyBuilder.SetContentIntent(pendingIntent);


            var notification = notyBuilder.Build();
            var notyManager  = GetSystemService(Context.NotificationService) as NotificationManager;

            notyManager.Notify(notyId, notification);
        }
示例#13
0
        public static async void ShowLocalNot(LocalNot not, Context context = null)
        {
            var cc      = context ?? Application.Context;
            var builder = new Notification.Builder(cc);

            builder.SetContentTitle(not.title);

            bool containsMultiLine = not.body.Contains("\n");

            if (Build.VERSION.SdkInt < BuildVersionCodes.O || !containsMultiLine)
            {
                builder.SetContentText(not.body);
            }
            builder.SetSmallIcon(not.smallIcon);
            builder.SetAutoCancel(not.autoCancel);
            builder.SetOngoing(not.onGoing);

            if (not.progress != -1)
            {
                builder.SetProgress(100, not.progress, false);
            }

            builder.SetVisibility(NotificationVisibility.Public);
            builder.SetOnlyAlertOnce(true);

            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                var channelId = $"{cc.PackageName}.general";
                var channel   = new NotificationChannel(channelId, "General", (NotificationImportance)not.notificationImportance);
                NotManager.CreateNotificationChannel(channel);

                builder.SetChannelId(channelId);

                if (not.bigIcon != null)
                {
                    if (not.bigIcon != "")
                    {
                        var bitmap = await GetImageBitmapFromUrl(not.bigIcon);

                        if (bitmap != null)
                        {
                            builder.SetLargeIcon(bitmap);
                            if (not.mediaStyle)
                            {
                                builder.SetStyle(new Notification.MediaStyle());                                 // NICER IMAGE
                            }
                        }
                    }
                }

                if (containsMultiLine)
                {
                    var b = new Notification.BigTextStyle();
                    b.BigText(not.body);
                    builder.SetStyle(b);
                }

                if (not.actions.Count > 0)
                {
                    List <Notification.Action> actions = new List <Notification.Action>();

                    for (int i = 0; i < not.actions.Count; i++)
                    {
                        var _resultIntent = new Intent(context, typeof(MainIntentService));
                        _resultIntent.PutExtra("data", not.actions[i].action);
                        var pending = PendingIntent.GetService(context, 3337 + i + not.id,
                                                               _resultIntent,
                                                               PendingIntentFlags.UpdateCurrent
                                                               );
                        actions.Add(new Notification.Action(not.actions[i].sprite, not.actions[i].name, pending));
                    }

                    builder.SetActions(actions.ToArray());
                }
            }

            builder.SetShowWhen(not.showWhen);
            if (not.when != null)
            {
                builder.SetWhen(CurrentTimeMillis((DateTime)not.when));
            }
            var stackBuilder = Android.Support.V4.App.TaskStackBuilder.Create(cc);

            var resultIntent = GetLauncherActivity(cc);

            if (not.data != "")
            {
                resultIntent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);
                var _data = Android.Net.Uri.Parse(not.data);                //"cloudstreamforms:tt0371746Name=Iron man=EndAll");
                resultIntent.SetData(_data);
                stackBuilder.AddNextIntent(resultIntent);
                var resultPendingIntent =
                    stackBuilder.GetPendingIntent(not.id, (int)PendingIntentFlags.UpdateCurrent);
                builder.SetContentIntent(resultPendingIntent);
            }
            else
            {
                stackBuilder.AddNextIntent(resultIntent);

                builder.SetContentIntent(GetCurrentPending());
            }

            try {
                NotManager.Notify(not.id, builder.Build());
            }
            catch { }
        }
示例#14
0
        internal static bool HandlePushNotification(Context context, Intent intent)
        {
            string message;

            if (!intent.Extras.ContainsKey("message"))
            {
                return(false);
            }

            message = intent.Extras.Get("message").ToString();
            var title = intent.Extras.Get("title").ToString();

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

            activityIntent.PutExtra("payload", payloadValue);
            activityIntent.SetFlags(ActivityFlags.SingleTop | ActivityFlags.ClearTop);
            var pendingIntent = PendingIntent.GetActivity(context, 0, activityIntent, PendingIntentFlags.UpdateCurrent);

            var n = new Notification.Builder(context);

            n.SetSmallIcon(Resource.Drawable.ic_successstatus);
            n.SetLights(global::Android.Graphics.Color.Blue, 300, 1000);
            n.SetContentIntent(pendingIntent);
            n.SetContentTitle(title);
            n.SetTicker(message);
            n.SetLargeIcon(global::Android.Graphics.BitmapFactory.DecodeResource(context.Resources, Resource.Drawable.icon));
            n.SetSmallIcon(Resource.Drawable.ic_trophy_white);
            n.SetContentText(message);
            n.SetVibrate(new long[] {
                200,
                200,
                100,
            });

            var nm = NotificationManager.FromContext(context);

            nm.Notify(0, n.Build());

            if (MainActivity.IsRunning)
            {
                try
                {
                    message.ToToast();
                    var payload = GetPayload(intent);
                    var pl      = JsonConvert.DeserializeObject <NotificationPayload>(payload);

                    if (payloadValue != null)
                    {
                        Device.BeginInvokeOnMainThread(() =>
                        {
                            MessagingCenter.Send <App, NotificationPayload>(App.Current, Messages.IncomingPayloadReceivedInternal, pl);
                        });
                    }
                }
                catch (Exception e)
                {
                    InsightsManager.Report(e, Insights.Severity.Error);
                }
            }

            return(true);
        }
        private async Task UpdateNotifications()
        {
            this._notificationManager.CancelAll();

            var res = Resources;
            var largeIcon = BitmapFactory.DecodeResource(res, Resource.Drawable.LargeIconEmpty);
            var colorAccent = Resources.GetColor(Resource.Color.Accent);
            var colorAccentDark = Resources.GetColor(Resource.Color.AccentDark);

            var timetable = ApplicationMain.ServiceLocator.GetInstance<Timetable>();
            var timetableDataset = await timetable.GetDatasetAsync().ConfigureAwait(false);
            var now = LogicalDateTime.Now;

            // 番組と番組の画像のマッピング
            var mapping = await GetProgramImageMappingAsync().ConfigureAwait(false);

            // 最新と次の番組をとってくる
            foreach (var program in timetableDataset.Data[now.DayOfWeek].Where(x => x.End >= now.Time).Take(2))
            {
                var isNowPlaying = program.IsNowPlaying;
                var intent = new Intent(this.ApplicationContext, typeof(MainActivity));
                var builder = new Notification.Builder(this.ApplicationContext)
                    .SetContentTitle(program.Title)
                    .SetContentText(isNowPlaying ? $"現在放送中: {program.End.ToString("hh\\:mm")}まで" : $"もうすぐスタート: {program.Start.ToString("hh\\:mm")}から")
                    .SetPriority((int)(isNowPlaying ? NotificationPriority.Max : NotificationPriority.Default))
                    .SetLocalOnly(true)
                    .SetOngoing(true)
                    .SetCategory(Notification.CategoryRecommendation)
                    .SetLargeIcon(largeIcon)
                    .SetSmallIcon(Resource.Drawable.SmallIcon)
                    .SetContentIntent(PendingIntent.GetActivity(this.ApplicationContext, 0, intent, PendingIntentFlags.UpdateCurrent))
                    .SetColor(colorAccentDark);

                var builderBigPicture = new Notification.BigPictureStyle(builder);

                try
                {
                    // 画像があればそれを使うしなければ文字を描画するぞい
                    if (mapping.ContainsKey(program.MailAddress) || mapping.ContainsKey(program.Title))
                    {
                        var imageUrl = mapping.ContainsKey(program.MailAddress)
                            ? mapping[program.MailAddress]
                            : mapping[program.Title];

                        using (var httpClient = new HttpClient())
                        using (var stream = await httpClient.GetStreamAsync(imageUrl).ConfigureAwait(false))
                        {
                            var bitmap = BitmapFactory.DecodeStream(stream);
                            builder.SetLargeIcon(bitmap);
                            builderBigPicture.BigPicture(bitmap);
                        }
                    }
                    else
                    {
                        var width = Resources.GetDimensionPixelSize(Resource.Dimension.RecommendationEmptyWidth);
                        var height = Resources.GetDimensionPixelSize(Resource.Dimension.RecommendationEmptyHeight);
                        var textSize = Resources.GetDimensionPixelSize(Resource.Dimension.RecommendationTextSize);
                        textSize = Resources.DisplayMetrics.ToDevicePixel(textSize);
                        width = Resources.DisplayMetrics.ToDevicePixel(width);
                        height = Resources.DisplayMetrics.ToDevicePixel(height);
                        var bitmap = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888);
                        using (var paint = new Paint() { TextSize = textSize, Color = Color.White, AntiAlias = true })
                        using (var textPaint = new TextPaint() { TextSize = textSize, Color = Color.White, AntiAlias = true })
                        using (var canvas = new Canvas(bitmap))
                        {
                            canvas.Save();

                            paint.Color = colorAccent;
                            canvas.DrawRect(0, 0, bitmap.Width, bitmap.Height, paint);

                            paint.Color = Color.White;
                            var textWidth = paint.MeasureText(program.Title);

                            // 回転する
                            // canvas.Rotate(45);
                            //canvas.DrawText(program.Title, 0, 0, paint);

                            // 
                            // canvas.DrawText(program.Title, (bitmap.Width / 2) - (textWidth / 2), (bitmap.Height / 2) + (paint.TextSize / 2), paint);

                            // 折り返しつつ描画
                            var margin = 16;
                            var textLayout = new StaticLayout(program.Title, textPaint, canvas.Width - (margin * 2), Layout.Alignment.AlignCenter, 1.0f, 0.0f, false);
                            canvas.Translate(margin, (canvas.Height / 2) - (textLayout.Height / 2));
                            textLayout.Draw(canvas);

                            canvas.Restore();
                        }
                        builder.SetLargeIcon(bitmap);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(Tag, ex.ToString());
                }

                this._notificationManager.Notify(program.Start.Ticks.GetHashCode(), builderBigPicture.Build());
            }
        }
        void ShowNotification(bool custom)
        {
            Resources res = Resources;
            NotificationManager notificationManager = (NotificationManager) GetSystemService (
                NotificationService);

            Notification.Builder builder = new Notification.Builder (this)
                .SetSmallIcon (Resource.Drawable.ic_stat_notify_example)
                .SetAutoCancel (true)
                .SetTicker (GetString(Resource.String.notification_text))
                .SetContentIntent (GetDialogPendingIntent ("Tapped the notification entry."));

            if (custom) {
                // Sets a custom content view for the notification, including an image button.
                RemoteViews layout = new RemoteViews (PackageName, Resource.Layout.notification);
                layout.SetTextViewText (Resource.Id.notification_title, GetString (Resource.String.app_name));
                layout.SetOnClickPendingIntent (Resource.Id.notification_button,
                    GetDialogPendingIntent ("Tapped the 'dialog' button in the notification."));
                builder.SetContent (layout);

                // Notifications in Android 3.0 now have a standard mechanism for displaying large
                // bitmaps such as contact avatars. Here, we load an example image and resize it to the
                // appropriate size for large bitmaps in notifications.
                Bitmap largeIconTemp = BitmapFactory.DecodeResource (res,
                    Resource.Drawable.notification_default_largeicon);
                Bitmap largeIcon = Bitmap.CreateScaledBitmap (
                    largeIconTemp,
                    res.GetDimensionPixelSize (Android.Resource.Dimension.NotificationLargeIconWidth),
                    res.GetDimensionPixelSize (Android.Resource.Dimension.NotificationLargeIconHeight),
                    false);
                largeIconTemp.Recycle ();

                builder.SetLargeIcon (largeIcon);

            } else {
                builder
                .SetNumber (7) // An example number.
                .SetContentTitle (GetString (Resource.String.app_name))
                .SetContentText (GetString (Resource.String.notification_text));
            }

            notificationManager.Notify (NotificationDefault, builder.Notification);
        }
        public void mostrarnotificacion()
        {
            var listapending = listapendingintents();


            RemoteViews contentView = new RemoteViews(PackageName, Resource.Layout.layoutminiplayeronline);

            if (linkactual.Trim().Length > 1)
            {
                try
                {
                    contentView.SetImageViewBitmap(Resource.Id.imageView1, ImageHelper.GetRoundedShape(GetImageBitmapFromUrl(linkactual)));
                    contentView.SetImageViewBitmap(Resource.Id.fondo1, ImageHelper.CreateBlurredImageFromUrl(this, 20, linkactual));
                }
                catch (Exception)
                {
                }
            }
            contentView.SetOnClickPendingIntent(Resource.Id.imageView1, listapending[5]);
            contentView.SetTextViewText(Resource.Id.textView1, tituloactual);
            contentView.SetOnClickPendingIntent(Resource.Id.imageView2, listapending[0]);
            contentView.SetOnClickPendingIntent(Resource.Id.imageView4, listapending[1]);
            contentView.SetOnClickPendingIntent(Resource.Id.imageView3, listapending[2]);
            contentView.SetOnClickPendingIntent(Resource.Id.imageView6, listapending[3]);
            contentView.SetOnClickPendingIntent(Resource.Id.imageView5, listapending[4]);


            /*
             *
             * 1-playpause
             * 2-siguiente
             * 3-anterior
             * 4-adelantar
             * 5-atrazar
             *
             */

            Notification.Action accion1 = new Notification.Action(Resource.Drawable.playpause, "Playpause", listapending[0]);
            Notification.Action accion2 = new Notification.Action(Resource.Drawable.skipnext, "Siguiente", listapending[1]);
            Notification.Action accion3 = new Notification.Action(Resource.Drawable.skipprevious, "Anterior", listapending[2]);
            Notification.Action accion4 = new Notification.Action(Resource.Drawable.skipforward, "adelantar", listapending[3]);
            Notification.Action accion5 = new Notification.Action(Resource.Drawable.skipbackward, "atrazar", listapending[4]);

#pragma warning disable CS0618 // El tipo o el miembro están obsoletos
            var nBuilder = new Notification.Builder(this);
#pragma warning restore CS0618 // El tipo o el miembro están obsoletos
            Notification.MediaStyle estilo = new Notification.MediaStyle();
            if (Mainmenu.gettearinstancia() != null)
            {
                //  estilo.SetMediaSession(mainmenu.gettearinstancia().mSession.SessionToken);

                estilo.SetShowActionsInCompactView(1, 2, 3);
            }
            if (Build.VERSION.SdkInt < BuildVersionCodes.Lollipop)
            {
#pragma warning disable 414
                try {
#pragma warning disable CS0618 // El tipo o el miembro están obsoletos
                    nBuilder.SetContent(contentView);
#pragma warning restore CS0618 // El tipo o el miembro están obsoletos
                }
                catch (Exception) {
                }

#pragma warning restore 414
            }
            else
            {
                nBuilder.SetStyle(estilo);
                nBuilder.SetLargeIcon(ImageHelper.GetImageBitmapFromUrl(linkactual));
                nBuilder.SetContentTitle(tituloactual);
                nBuilder.SetContentText("Desde: " + Mainmenu.gettearinstancia().devicename);
                nBuilder.AddAction(accion5);
                nBuilder.AddAction(accion3);
                nBuilder.AddAction(accion1);
                nBuilder.AddAction(accion2);
                nBuilder.AddAction(accion4);
                nBuilder.SetContentIntent(listapending[5]);
                nBuilder.SetColor(Android.Graphics.Color.ParseColor("#ce2c2b"));
            }
            nBuilder.SetOngoing(true);

            nBuilder.SetSmallIcon(Resource.Drawable.play);

            Notification notification = nBuilder.Build();
            StartForeground(19248736, notification);
        }
        private void CreateBuilder(IMediaItem mediaItem)
        {
            var builder = new Notification.Builder(Application.Context, channelId);

            builder.SetChannelId(channelId);

            //Configure builder
            builder.SetContentTitle(mediaItem.Title);
            builder.SetContentText(mediaItem.Artist);
            builder.SetWhen(0);

            if (AndroidAudioPlayer.SharedInstance.IsPlaying)
            {
                builder.SetOngoing(true);
                builder.SetSmallIcon(Android.Resource.Drawable.IcMediaPlay);
            }
            else
            {
                builder.SetOngoing(false);
                Intent        dismissIntent        = new Intent(ButtonEvents.AudioControlsDestroy);
                PendingIntent dismissPendingIntent = PendingIntent.GetBroadcast(Application.Context, 1, dismissIntent, 0);
                builder.SetDeleteIntent(dismissPendingIntent);
                builder.SetSmallIcon(Android.Resource.Drawable.IcMediaPause);
            }

            //If 5.0 >= set the controls to be visible on lockscreen
            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop)
            {
                builder.SetVisibility(NotificationVisibility.Public);
            }

            if (!string.IsNullOrWhiteSpace(mediaItem.AlbumArtUrl))
            {
                try
                {
                    var bitmap = new AsyncImageDownloader().Execute(new string[] { mediaItem.AlbumArtUrl });
                    builder.SetLargeIcon(bitmap.GetResult());
                }
                catch (Java.Lang.Exception exc)
                {
                    Console.WriteLine($"Unable to find Album Art URL for {mediaItem.AlbumArtUrl}");
                    Console.WriteLine(exc.ToString());
                }
            }

            Intent resultIntent = new Intent(Application.Context, typeof(Activity));

            resultIntent.SetAction(Intent.ActionMain);
            resultIntent.AddCategory(Intent.CategoryLauncher);
            PendingIntent resultPendingIntent = PendingIntent.GetActivity(Application.Context, 0, resultIntent, PendingIntentFlags.UpdateCurrent);

            builder.SetContentIntent(resultPendingIntent);

            //Controls
            var controlsCount = 0;

            // Previous
            controlsCount++;
            builder.AddAction(previousAction);

            // Play/Pause
            builder.AddAction(pauseAction);

            // Next
            controlsCount++;
            builder.AddAction(nextAction);

            // Close
            //controlsCount++;
            //builder.AddAction(destroyAction);

            // If 5.0 >= use MediaStyle
            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop)
            {
                int[] args = new int[controlsCount];
                for (int i = 0; i < controlsCount; ++i)
                {
                    args[i] = i;
                }
                var style = new Notification.MediaStyle();
                style.SetShowActionsInCompactView(args);
                builder.SetStyle(style);
            }
            notificationBuilder = builder;
        }
		/*
		 * Invoked when showNotificationButton is clicked.
		 * Creates a new notification and sets metadata passed as arguments.
		 */
		public Notification CreateNotification(Priority priority, Category category, Uri contactUri)
		{
			var builder = new Notification.Builder (Activity)
				.SetContentTitle ("Notification with other metadata")
				.SetSmallIcon (Resource.Drawable.ic_launcher_notification)
				.SetPriority ((int)priority.priority)
				.SetCategory (category.ToString ())
				.SetContentText(string.Format("Category {0}, Priority {1}",category.ToString(),priority.ToString()));
			if (contactUri != null) {
				builder.AddPerson (contactUri.ToString ());
				Bitmap photoBitmap = LoadBitmapFromContactUri (contactUri);
				if (photoBitmap != null)
					builder.SetLargeIcon (photoBitmap);
			}
			return builder.Build ();
		}
示例#20
0
        protected override void OnCreate(Bundle bundle)
        {
            TabLayoutResource = Resource.Layout.tabs;
            ToolbarResource   = Resource.Layout.toolbar;

            base.OnCreate(bundle);

            notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;

            global::Xamarin.Forms.Forms.Init(this, bundle);
            var fooApp = new App(new AndroidInitializer());

            #region 檢查是否是由通知開啟 App,並且依據通知,切換到適當頁面

            //自訂通知被點擊後的動作
            //當通知出現在通知欄之後,在習慣的趨使下,有很大的機率會被使用者點擊。
            //所以應該要實作出通知被點擊後的動作,好比開啟哪個Activity之類的。
            //通知被點擊後的動作可以使用PendingIntent來實作,PendingIntent並不是一個Intent,它是一個Intent的容器,
            // 可以傳入context物件,並以這個context的身份來做一些事情,例如開啟Activity、開啟Service,或是發送Broadcast。
            // 如果要使通知可以在被點擊之後做點什麼事,可以使用Notification.Builder的setContentIntent方法來替通知加入PendingIntent

            fooLocalNotificationPayload = null;
            if (Intent.Extras != null)
            {
                if (Intent.Extras.ContainsKey("NotificationObject"))
                {
                    string fooNotificationObject = Intent.Extras.GetString("NotificationObject", "");
                    fooLocalNotificationPayload = JsonConvert.DeserializeObject <LocalNotificationPayload>(fooNotificationObject);
                }
            }
            #endregion

            XFLocalNotificationDroid.App.fooLocalNotificationPayload = fooLocalNotificationPayload;
            LoadApplication(new App(new AndroidInitializer()));

            #region 訂閱要發送本地通知的事件
            // 取得 Xamarin.Forms 中的 Prism 注入物件管理容器
            IUnityContainer myContainer = (App.Current as PrismApplication).Container;
            var             fooEvent    = myContainer.Resolve <IEventAggregator>().GetEvent <LocalNotificationEvent>().Subscribe(x =>
            {
                #region 建立本地訊息通知物件
                Notification.Builder builder = new Notification.Builder(this)
                                               .SetContentTitle(x.ContentTitle)
                                               .SetContentText(x.ContentText)
                                               .SetSmallIcon(Resource.Drawable.ic_notification)
                                               .SetAutoCancel(true);

                // 決定是否要顯示大圖示
                if (x.LargeIcon)
                {
                    builder.SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.monkey_icon));
                }

                #region 針對不同通知類型作出設定
                switch (x.Style)
                {
                case LocalNotificationStyleEnum.Normal:
                    break;

                case LocalNotificationStyleEnum.BigText:
                    //builder.SetContentText(x.ContentText);
                    var textStyle = new Notification.BigTextStyle();
                    textStyle.BigText(x.ContentText);
                    textStyle.SetSummaryText(x.SummaryText);

                    builder.SetStyle(textStyle);
                    break;

                case LocalNotificationStyleEnum.Inbox:
                    var inboxStyle = new Notification.InboxStyle();
                    foreach (var item in x.InboxStyleList)
                    {
                        inboxStyle.AddLine(item);
                    }
                    inboxStyle.SetSummaryText(x.SummaryText);

                    builder.SetStyle(inboxStyle);
                    break;

                case LocalNotificationStyleEnum.Image:
                    var picStyle = new Notification.BigPictureStyle();
                    picStyle.BigPicture(BitmapFactory.DecodeResource(Resources, Resource.Drawable.x_bldg));
                    picStyle.SetSummaryText(x.SummaryText);

                    builder.SetStyle(picStyle);
                    break;

                default:
                    break;
                }
                #endregion

                #region 設定 visibility
                switch (x.Visibility)
                {
                case LocalNotificationVisibilityEnum.Public:
                    builder.SetVisibility(NotificationVisibility.Public);
                    break;

                case LocalNotificationVisibilityEnum.Private:
                    builder.SetVisibility(NotificationVisibility.Private);
                    break;

                case LocalNotificationVisibilityEnum.Secret:
                    builder.SetVisibility(NotificationVisibility.Secret);
                    break;

                default:
                    break;
                }
                #endregion

                #region 設定 priority
                switch (x.Priority)
                {
                case LocalNotificationPriorityEnum.Default:
                    builder.SetPriority((int)NotificationPriority.Default);
                    break;

                case LocalNotificationPriorityEnum.High:
                    builder.SetPriority((int)NotificationPriority.High);
                    break;

                case LocalNotificationPriorityEnum.Low:
                    builder.SetPriority((int)NotificationPriority.Low);
                    break;

                case LocalNotificationPriorityEnum.Maximum:
                    builder.SetPriority((int)NotificationPriority.Max);
                    break;

                case LocalNotificationPriorityEnum.Minimum:
                    builder.SetPriority((int)NotificationPriority.Min);
                    break;

                default:
                    break;
                }
                #endregion

                #region 設定 category
                switch (x.Category)
                {
                case LocalNotificationCategoryEnum.Call:
                    builder.SetCategory(LocalNotificationCategoryEnum.Call.ToString());
                    break;

                case LocalNotificationCategoryEnum.Message:
                    builder.SetCategory(LocalNotificationCategoryEnum.Message.ToString());
                    break;

                case LocalNotificationCategoryEnum.Alarm:
                    builder.SetCategory(LocalNotificationCategoryEnum.Alarm.ToString());
                    break;

                case LocalNotificationCategoryEnum.Email:
                    builder.SetCategory(LocalNotificationCategoryEnum.Email.ToString());
                    break;

                case LocalNotificationCategoryEnum.Event:
                    builder.SetCategory(LocalNotificationCategoryEnum.Event.ToString());
                    break;

                case LocalNotificationCategoryEnum.Promo:
                    builder.SetCategory(LocalNotificationCategoryEnum.Promo.ToString());
                    break;

                case LocalNotificationCategoryEnum.Progress:
                    builder.SetCategory(LocalNotificationCategoryEnum.Progress.ToString());
                    break;

                case LocalNotificationCategoryEnum.Social:
                    builder.SetCategory(LocalNotificationCategoryEnum.Social.ToString());
                    break;

                case LocalNotificationCategoryEnum.Error:
                    builder.SetCategory(LocalNotificationCategoryEnum.Error.ToString());
                    break;

                case LocalNotificationCategoryEnum.Transport:
                    builder.SetCategory(LocalNotificationCategoryEnum.Transport.ToString());
                    break;

                case LocalNotificationCategoryEnum.System:
                    builder.SetCategory(LocalNotificationCategoryEnum.System.ToString());
                    break;

                case LocalNotificationCategoryEnum.Service:
                    builder.SetCategory(LocalNotificationCategoryEnum.Service.ToString());
                    break;

                case LocalNotificationCategoryEnum.Recommendation:
                    builder.SetCategory(LocalNotificationCategoryEnum.Recommendation.ToString());
                    break;

                case LocalNotificationCategoryEnum.Status:
                    builder.SetCategory(LocalNotificationCategoryEnum.Status.ToString());
                    break;

                default:
                    break;
                }
                #endregion

                #region 準備設定當使用者點選通知之後要做的動作
                // Setup an intent for SecondActivity:
                Intent secondIntent = new Intent(this, typeof(MainActivity));

                // 設定當使用點選這個通知之後,要傳遞過去的資料
                secondIntent.PutExtra("NotificationObject", JsonConvert.SerializeObject(x));

                // 若在首頁且使用者按下回上頁實體按鈕,則會離開這個 App
                TaskStackBuilder stackBuilder = TaskStackBuilder.Create(this);

                stackBuilder.AddNextIntent(secondIntent);
                PendingIntent pendingIntent = stackBuilder.GetPendingIntent(pendingIntentId++, PendingIntentFlags.OneShot);

                // Uncomment this code to setup an intent so that notifications return to this app:
                // Intent intent = new Intent (this, typeof(MainActivity));
                // const int pendingIntentId = 0;
                // pendingIntent = PendingIntent.GetActivity (this, pendingIntentId, intent, PendingIntentFlags.OneShot);
                // builder.SetContentText("Hello World! This is my first action notification!");

                // Launch SecondActivity when the users taps the notification:
                builder.SetContentIntent(pendingIntent);

                // 產生一個 notification 物件
                Notification notification = builder.Build();

                #region 決定是否要發出聲音
                if (x.Sound)
                {
                    notification.Defaults |= NotificationDefaults.Sound;
                }
                #endregion

                #region 決定是否要有震動
                if (x.Vibrate)
                {
                    notification.Defaults |= NotificationDefaults.Vibrate;
                }
                #endregion


                // 顯示本地通知:
                notificationManager.Notify(notificationId++, notification);

                // 解開底下程式碼註解,將會於五秒鐘之後,才會發生本地通知
                // Thread.Sleep(5000);
                // builder.SetContentTitle("Updated Notification");
                // builder.SetContentText("Changed to this message after five seconds.");
                // notification = builder.Build();
                // notificationManager.Notify(notificationId, notification);
                #endregion
                #endregion
            });
            #endregion
        }
        public void mostrarnotificacion()
        {
            List <PendingIntent> listapending = listapendingintents();

            RemoteViews contentView = new RemoteViews(PackageName, Resource.Layout.layoutminiplayer);

            if (linkactual.Trim().Length > 1)
            {
                try
                {
                    // contentView.SetImageViewBitmap(Resource.Id.imageView1, playeroffline.gettearinstancia().imageneses.First(info => info.GenerationId == playeroffline.gettearinstancia().diccionario[tituloactual]));
                    contentView.SetImageViewBitmap(Resource.Id.fondo1, ImageHelper.CreateBlurredImageFromPortrait(this, 20, linkactual));
                }
                catch (Exception) {
                }

                ///   contentView.SetImageViewBitmap(Resource.Id.fondo1, clasesettings.CreateBlurredImageoffline(this, 20, linkactual));
            }
            contentView.SetTextViewText(Resource.Id.textView1, tituloactual);
            contentView.SetOnClickPendingIntent(Resource.Id.imageView1, listapending[5]);
            contentView.SetOnClickPendingIntent(Resource.Id.imageView2, listapending[0]);
            contentView.SetOnClickPendingIntent(Resource.Id.imageView4, listapending[1]);
            contentView.SetOnClickPendingIntent(Resource.Id.imageView3, listapending[2]);
            contentView.SetOnClickPendingIntent(Resource.Id.imageView6, listapending[3]);
            contentView.SetOnClickPendingIntent(Resource.Id.imageView5, listapending[4]);



            Notification.Action accion1 = new Notification.Action(Resource.Drawable.playpause, "Playpause", listapending[0]);
            Notification.Action accion2 = new Notification.Action(Resource.Drawable.skipnext, "Siguiente", listapending[1]);
            Notification.Action accion3 = new Notification.Action(Resource.Drawable.skipprevious, "Anterior", listapending[2]);
            Notification.Action accion4 = new Notification.Action(Resource.Drawable.skipforward, "adelantar", listapending[3]);
            Notification.Action accion5 = new Notification.Action(Resource.Drawable.skipbackward, "atrazar", listapending[4]);

            /*
             *
             * 1-playpause
             * 2-siguiente
             * 3-anterior
             * 4-adelantar
             * 5-atrazar
             *
             */



            Notification.MediaStyle estilo = new Notification.MediaStyle();
            if (playeroffline.gettearinstancia() != null)
            {
                estilo.SetMediaSession(playeroffline.gettearinstancia().mSession.SessionToken);

                estilo.SetShowActionsInCompactView(1, 2, 3);
            }


#pragma warning disable CS0618 // El tipo o el miembro están obsoletos
            var nBuilder = new Notification.Builder(this);
#pragma warning restore CS0618 // El tipo o el miembro están obsoletos

            if (Build.VERSION.SdkInt < BuildVersionCodes.Lollipop)
            {
#pragma warning disable 414
                try
                {
#pragma warning disable CS0618 // El tipo o el miembro están obsoletos
                    nBuilder.SetContent(contentView);
#pragma warning restore CS0618 // El tipo o el miembro están obsoletos
                }
                catch (Exception) {
                }

#pragma warning restore 414
            }
            else
            {
                nBuilder.SetStyle(estilo);
                nBuilder.SetLargeIcon(GetImageBitmapFromUrl(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits/" + playeroffline.gettearinstancia().linkeses[playeroffline.gettearinstancia().nombreses.IndexOf(tituloactual)].Split('=')[1]));
                nBuilder.SetContentTitle(tituloactual);

                nBuilder.SetContentText(playeroffline.gettearinstancia().linkeses[playeroffline.gettearinstancia().nombreses.IndexOf(tituloactual)]);
                nBuilder.AddAction(accion5);
                nBuilder.AddAction(accion3);
                nBuilder.AddAction(accion1);
                nBuilder.AddAction(accion2);
                nBuilder.AddAction(accion4);
                nBuilder.SetContentIntent(listapending[5]);
                nBuilder.SetColor(Android.Graphics.Color.ParseColor("#ce2c2b"));

                //  nBuilder.AddAction()
            }

            nBuilder.SetOngoing(true);
            nBuilder.SetSmallIcon(Resource.Drawable.play);
            Notification notification = nBuilder.Build();
            StartForeground(19248736, notification);
            listapending.Clear();
        }
示例#22
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set the view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

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

            //..........................................................................
            // Edit box:

            // Find the notification edit text box in the layout:
            notifyMsg = FindViewById <EditText>(Resource.Id.notifyText);

            //..........................................................................
            // Selection Spinners:
            // The spinners in this file use the strings defined in Resources/values/arrays.xml.

            // Find the Style spinner in the layout and configure its adapter.
            Spinner styleSpinner = FindViewById <Spinner>(Resource.Id.styleSpinner);
            var     styleAdapter = ArrayAdapter.CreateFromResource(this,
                                                                   Resource.Array.notification_style,
                                                                   Android.Resource.Layout.SimpleSpinnerDropDownItem);

            styleSpinner.Adapter = styleAdapter;

            // Handler for Style spinner, changes the text in the text box:
            styleSpinner.ItemSelected += new EventHandler <AdapterView.ItemSelectedEventArgs> (styleSpinnerSelected);

            // Find the Visibility spinner in the layout and configure its adapter:
            Spinner visibilitySpinner = FindViewById <Spinner>(Resource.Id.visibilitySpinner);
            var     visibilityAdapter = ArrayAdapter.CreateFromResource(this,
                                                                        Resource.Array.notification_visibility,
                                                                        Android.Resource.Layout.SimpleSpinnerDropDownItem);

            visibilitySpinner.Adapter = visibilityAdapter;

            // Find the Priority spinner in the layout and configure its adapter:
            Spinner prioritySpinner = FindViewById <Spinner>(Resource.Id.prioritySpinner);
            var     priorityAdapter = ArrayAdapter.CreateFromResource(this,
                                                                      Resource.Array.notification_priority,
                                                                      Android.Resource.Layout.SimpleSpinnerDropDownItem);

            prioritySpinner.Adapter = priorityAdapter;

            // Find the Category spinner in the layout and configure its adapter:
            Spinner categorySpinner = FindViewById <Spinner>(Resource.Id.categorySpinner);
            var     categoryAdapter = ArrayAdapter.CreateFromResource(this,
                                                                      Resource.Array.notification_category,
                                                                      Android.Resource.Layout.SimpleSpinnerDropDownItem);

            categorySpinner.Adapter = categoryAdapter;

            // Handler for Style spinner: changes the text in the text box:
            styleSpinner.ItemSelected += new EventHandler <AdapterView.ItemSelectedEventArgs> (styleSpinnerSelected);

            //..........................................................................
            // Option Switches:

            // Get large-icon, sound, and vibrate switches from the layout:
            Switch largeIconSw = FindViewById <Switch>(Resource.Id.largeIconSwitch);
            Switch soundSw     = FindViewById <Switch>(Resource.Id.soundSwitch);
            Switch vibrateSw   = FindViewById <Switch>(Resource.Id.vibrateSwitch);

            //..........................................................................
            // Notification Launch button:

            // Get notification launch button from the layout:
            Button launchBtn = FindViewById <Button>(Resource.Id.launchButton);

            // Handler for the notification launch button. When this button is clicked, this
            // handler code takes the following steps, in order:
            //
            //  1. Instantiates the builder.
            //  2. Calls methods on the builder to optionally plug in the large icon, extend
            //     the style (if called for by a spinner selection), set the visibility, set
            //     the priority, and set the category.
            //  3. Uses the builder to instantiate the notification.
            //  4. Turns on sound and vibrate (if selected).
            //  5. Uses the Notification Manager to launch the notification.

            launchBtn.Click += delegate
            {
                // Instantiate the notification builder:
                Notification.Builder builder = new Notification.Builder(this)
                                               .SetContentTitle("Sample Notification")
                                               .SetContentText(notifyMsg.Text)
                                               .SetSmallIcon(Resource.Drawable.ic_notification)
                                               .SetAutoCancel(true);

                // Add large icon if selected:
                if (largeIconSw.Checked)
                {
                    builder.SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.monkey_icon));
                }

                // Extend style based on Style spinner selection.
                switch (styleSpinner.SelectedItem.ToString())
                {
                case "Big Text":

                    // Extend the message with the big text format style. This will
                    // use a larger screen area to display the notification text.

                    // Set the title for demo purposes:
                    builder.SetContentTitle("Big Text Notification");

                    // Using the Big Text style:
                    var textStyle = new Notification.BigTextStyle();

                    // Use the text in the edit box at the top of the screen.
                    textStyle.BigText(notifyMsg.Text);
                    textStyle.SetSummaryText("The summary text goes here.");

                    // Plug this style into the builder:
                    builder.SetStyle(textStyle);
                    break;

                case "Inbox":

                    // Present the notification in inbox format instead of normal text style.
                    // Note that this does not display the notification message entered
                    // in the edit text box; instead, it displays the fake email inbox
                    // summary constructed below.

                    // Using the inbox style:
                    var inboxStyle = new Notification.InboxStyle();

                    // Set the title of the notification:
                    builder.SetContentTitle("5 new messages");
                    builder.SetContentText("*****@*****.**");

                    // Generate inbox notification text:
                    inboxStyle.AddLine("Cheeta: Bananas on sale");
                    inboxStyle.AddLine("George: Curious about your blog post");
                    inboxStyle.AddLine("Nikko: Need a ride to Evolve?");
                    inboxStyle.SetSummaryText("+2 more");

                    // Plug this style into the builder:
                    builder.SetStyle(inboxStyle);
                    break;

                case "Image":

                    // Extend the message with image (big picture) format style. This displays
                    // the Resources/drawables/x_bldg.jpg image in the notification body.

                    // Set the title for demo purposes:
                    builder.SetContentTitle("Image Notification");

                    // Using the Big Picture style:
                    var picStyle = new Notification.BigPictureStyle();

                    // Convert the image file to a bitmap before passing it into the style
                    // (there is no exception handler since we know the size of the image):
                    picStyle.BigPicture(BitmapFactory.DecodeResource(Resources, Resource.Drawable.x_bldg));
                    picStyle.SetSummaryText("The summary text goes here.");

                    // Alternately, uncomment this code to use an image from the SD card.
                    // (In production code, wrap DecodeFile in an exception handler in case
                    // the image is too large and throws an out of memory exception.):
                    // BitmapFactory.Options options = new BitmapFactory.Options();
                    // options.InSampleSize = 2;
                    // string imagePath = "/sdcard/Pictures/my-tshirt.jpg";
                    // picStyle.BigPicture(BitmapFactory.DecodeFile(imagePath, options));
                    // picStyle.SetSummaryText("Check out my new T-shirt!");

                    // Plug this style into the builder:
                    builder.SetStyle(picStyle);
                    break;

                default:
                    // Normal text notification is the default.
                    break;
                }

                // Set visibility based on Visibility spinner selection:
                switch (visibilitySpinner.SelectedItem.ToString())
                {
                case "Public":
                    builder.SetVisibility(NotificationVisibility.Public);
                    break;

                case "Private":
                    builder.SetVisibility(NotificationVisibility.Private);
                    break;

                case "Secret":
                    builder.SetVisibility(NotificationVisibility.Secret);
                    break;
                }

                // Set priority based on Priority spinner selection:
                switch (prioritySpinner.SelectedItem.ToString())
                {
                case "High":
                    builder.SetPriority((int)NotificationPriority.High);
                    break;

                case "Low":
                    builder.SetPriority((int)NotificationPriority.Low);
                    break;

                case "Maximum":
                    builder.SetPriority((int)NotificationPriority.Max);
                    break;

                case "Minimum":
                    builder.SetPriority((int)NotificationPriority.Min);
                    break;

                default:
                    builder.SetPriority((int)NotificationPriority.Default);
                    break;
                }

                // Set category based on Category spinner selection:
                switch (categorySpinner.SelectedItem.ToString())
                {
                case "Call":
                    builder.SetCategory(Notification.CategoryCall);
                    break;

                case "Message":
                    builder.SetCategory(Notification.CategoryMessage);
                    break;

                case "Alarm":
                    builder.SetCategory(Notification.CategoryAlarm);
                    break;

                case "Email":
                    builder.SetCategory(Notification.CategoryEmail);
                    break;

                case "Event":
                    builder.SetCategory(Notification.CategoryEvent);
                    break;

                case "Promo":
                    builder.SetCategory(Notification.CategoryPromo);
                    break;

                case "Progress":
                    builder.SetCategory(Notification.CategoryProgress);
                    break;

                case "Social":
                    builder.SetCategory(Notification.CategorySocial);
                    break;

                case "Error":
                    builder.SetCategory(Notification.CategoryError);
                    break;

                case "Transport":
                    builder.SetCategory(Notification.CategoryTransport);
                    break;

                case "System":
                    builder.SetCategory(Notification.CategorySystem);
                    break;

                case "Service":
                    builder.SetCategory(Notification.CategoryService);
                    break;

                case "Recommendation":
                    builder.SetCategory(Notification.CategoryRecommendation);
                    break;

                case "Status":
                    builder.SetCategory(Notification.CategoryStatus);
                    break;

                default:
                    builder.SetCategory(Notification.CategoryStatus);
                    break;
                }

                // Setup an intent for SecondActivity:
                Intent secondIntent = new Intent(this, typeof(SecondActivity));

                // Pass the current notification string value to SecondActivity:
                secondIntent.PutExtra("message", notifyMsg.Text);

                // Pressing the Back button in SecondActivity exits the app:
                TaskStackBuilder stackBuilder = TaskStackBuilder.Create(this);

                // Add the back stack for the intent:
                stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(SecondActivity)));

                // Push the intent (that starts SecondActivity) onto the stack. The
                // pending intent can be used only once (one shot):
                stackBuilder.AddNextIntent(secondIntent);
                const int     pendingIntentId = 0;
                PendingIntent pendingIntent   = stackBuilder.GetPendingIntent(pendingIntentId, PendingIntentFlags.OneShot);

                // Uncomment this code to setup an intent so that notifications return to this app:
                // Intent intent = new Intent (this, typeof(MainActivity));
                // const int pendingIntentId = 0;
                // pendingIntent = PendingIntent.GetActivity (this, pendingIntentId, intent, PendingIntentFlags.OneShot);
                // builder.SetContentText("Hello World! This is my first action notification!");

                // Launch SecondActivity when the users taps the notification:
                builder.SetContentIntent(pendingIntent);

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

                // Turn on sound if the sound switch is on:
                if (soundSw.Checked)
                {
                    notification.Defaults |= NotificationDefaults.Sound;
                }

                // Turn on vibrate if the sound switch is on:
                if (vibrateSw.Checked)
                {
                    notification.Defaults |= NotificationDefaults.Vibrate;
                }

                // Notification ID used for all notifications in this app.
                // Reusing the notification ID prevents the creation of
                // numerous different notifications as the user experiments
                // with different notification settings -- each launch reuses
                // and updates the same notification.
                const int notificationId = 1;

                // Launch notification:
                notificationManager.Notify(notificationId, notification);

                // Uncomment this code to update the notification 5 seconds later:
                // Thread.Sleep(5000);
                // builder.SetContentTitle("Updated Notification");
                // builder.SetContentText("Changed to this message after five seconds.");
                // notification = builder.Build();
                // 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);
        }