Beispiel #1
0
        internal static void SendNotification(Context context, string title, string body)
        {
            // Set up an intent so that tapping the notifications returns to this app:
            Intent intent = new Intent(context, typeof(MainActivity));

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

            Notification.Builder notificationBuilder = new Notification.Builder(context)
                                                       .SetSmallIcon(Resource.Drawable.menu_events)
                                                       .SetContentTitle(title)
                                                       .SetContentText(body)
                                                       .SetContentIntent(pendingIntent)
                                                       .SetAutoCancel(autoCancel: true);

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

            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
            {
                notificationBuilder.SetChannelId(NewMeetupChannelID);
            }

            notificationManager.Notify(Settings.GetUniqueNotificationID(), notificationBuilder.Build());
        }
Beispiel #2
0
        public override void OnReceive(Context context, Intent intent)
        {
            using (var builder = new Notification.Builder(Application.Context))
            {
                builder.SetContentTitle(TranslationCodeExtension.GetTranslation("HalfWorkTitle"))
                .SetContentText(TranslationCodeExtension.GetTranslation("HalfWorkText"))
                .SetAutoCancel(true)
                .SetSmallIcon(Resource.Drawable.icon);

                var manager = (NotificationManager)Application.Context.GetSystemService(Context.NotificationService);

                if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
                {
                    var channelId = $"{Application.Context.PackageName}.general";
                    var channel   = new NotificationChannel(channelId, "General", NotificationImportance.Default);

                    manager.CreateNotificationChannel(channel);

                    builder.SetChannelId(channelId);
                }

                var resultIntent = GetLauncherActivity();
                resultIntent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);
                var stackBuilder = Android.Support.V4.App.TaskStackBuilder.Create(Application.Context);
                stackBuilder.AddNextIntent(resultIntent);
                var resultPendingIntent =
                    stackBuilder.GetPendingIntent(0, (int)PendingIntentFlags.UpdateCurrent);
                builder.SetContentIntent(resultPendingIntent);

                manager.Notify(2, builder.Build());
                CrossVibrate.Current.Vibration(TimeSpan.FromMilliseconds(150));

                stackBuilder.Dispose();
            }
        }
Beispiel #3
0
        private void CreateNotification()
        {
            var notificationManager = (NotificationManager)GetSystemService(NotificationService);

            var notificationBuilder = new Notification.Builder(this)
                                      .SetSmallIcon(Resource.Drawable.ic_pod)
                                      .SetContentTitle("OmniCore")
                                      .SetContentText("Service is running");

            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
            {
                var channelId = "OmniCoreGeneralNotifications";
                var channel   = new NotificationChannel(channelId, "Service Notifications", NotificationImportance.Default)
                {
                    Description = "General service notifications."
                };

                notificationManager.CreateNotificationChannel(channel);
                notificationBuilder.SetChannelId(channelId);
            }
            var notification = notificationBuilder.Build();

            notificationManager.Notify(1, notification);
            StartForeground(1, notification);
        }
Beispiel #4
0
        public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
        {
            base.OnStartCommand(intent, flags, startId);

            this.RunWithFaultHandler(() => this.ProcessColdStart());

            _serverPollingTimer = new Timer(callback => this.RunWithFaultHandler(() => this.PollServer()), null, 100, 3000);

            var notification = new Notification.Builder(this)

                               .SetContentTitle(PollingServiceConstants.EnvironmentNotificationTitle)
                               .SetContentText(PollingServiceConstants.ServiceStartedMessage)
                               .SetSmallIcon(Resource.Mipmap.icon)
                               .SetContentIntent(this.BuildIntentToShowMainActivity())
                               .SetOngoing(true);

            var notificationChannel = this.CreateNotificationChannelIfNecessary(true);

            if (notificationChannel != null)
            {
                notification.SetChannelId(notificationChannel.Id);
            }

            this.StartForeground(PollingServiceConstants.ServiceRunningNotificationId, notification.Build());

            return(StartCommandResult.Sticky);
        }
        void CreateNotification()
        {
            NotificationManager manager = Android.App.Application.Context.GetSystemService(Context.NotificationService) as NotificationManager;
            var builder = new Notification.Builder(Android.App.Application.Context);

            builder.SetContentTitle("Test Notification");
            builder.SetContentText("This is the body");
            builder.SetAutoCancel(true);
            builder.SetSmallIcon(Resource.Drawable.clipboard);

            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                var channelId = "com.companyname.briefing.general";
                var channel   = new NotificationChannel(channelId, "General", NotificationImportance.Default);

                manager.CreateNotificationChannel(channel);

                builder.SetChannelId(channelId);
            }
            var resultIntent = Android.App.Application.Context.PackageManager.GetLaunchIntentForPackage(Android.App.Application.Context.PackageName);

            resultIntent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);
            var stackBuilder = Android.Support.V4.App.TaskStackBuilder.Create(Android.App.Application.Context);

            stackBuilder.AddNextIntent(resultIntent);
            var resultPendingIntent =
                stackBuilder.GetPendingIntent(0, (int)PendingIntentFlags.UpdateCurrent);

            builder.SetContentIntent(resultPendingIntent);

            manager.Notify(0, builder.Build());
        }
Beispiel #6
0
    public void On(string title, string body, int id)
    {
        Context       context       = Forms.Context;
        Intent        intent        = new Intent(context, typeof(MainActivity));
        PendingIntent pendingIntent = PendingIntent.GetActivity(context, 0, intent, 0);

        //デフォルトの通知音を取得
        Android.Net.Uri uri       = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
        string          channelId = "TLExtension";

        Notification.Builder builder = new Notification.Builder(context)
                                       .SetContentTitle(title)
                                       .SetContentText(body)
                                       .SetSmallIcon(Resource.Mipmap.icon);
        Notification notification = builder.Build();

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

        if (Build.VERSION.SdkInt >= Build.VERSION_CODES.O)
        {
            NotificationChannel notificationChannel = notificationManager.GetNotificationChannel(channelId);
            if (notificationChannel == null)
            {
                NotificationImportance importance = NotificationImportance.High;
                notificationChannel = new NotificationChannel(channelId, "Use in TL Extension", importance);
                notificationChannel.EnableLights(true);
                notificationChannel.EnableVibration(true);
                notificationManager.CreateNotificationChannel(notificationChannel);
            }
            builder = builder.SetChannelId(channelId);
        }

        notificationManager.Notify(id, notification);
    }
Beispiel #7
0
        private void NotifyToAutofill(string uri, NotificationManager notificationManager)
        {
            if (notificationManager == null || string.IsNullOrWhiteSpace(uri))
            {
                return;
            }

            var now    = Java.Lang.JavaSystem.CurrentTimeMillis();
            var intent = new Intent(this, typeof(AutofillActivity));

            intent.PutExtra("uri", uri);
            intent.SetFlags(ActivityFlags.NewTask | ActivityFlags.SingleTop | ActivityFlags.ClearTop);
            var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.UpdateCurrent);

            var notificationContent = Build.VERSION.SdkInt > BuildVersionCodes.KitkatWatch ?
                                      AppResources.BitwardenAutofillServiceNotificationContent :
                                      AppResources.BitwardenAutofillServiceNotificationContentOld;

            var builder = new Notification.Builder(this);

            builder.SetSmallIcon(Resource.Drawable.notification_sm)
            .SetContentTitle(AppResources.BitwardenAutofillService)
            .SetContentText(notificationContent)
            .SetTicker(notificationContent)
            .SetWhen(now)
            .SetContentIntent(pendingIntent);

            if (Build.VERSION.SdkInt > BuildVersionCodes.KitkatWatch)
            {
                builder.SetVisibility(NotificationVisibility.Secret)
                .SetColor(global::Android.Support.V4.Content.ContextCompat.GetColor(ApplicationContext,
                                                                                    Resource.Color.primary));
            }

            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                if (_notificationChannel == null)
                {
                    _notificationChannel = new NotificationChannel("bitwarden_autofill_service",
                                                                   AppResources.AutofillService, NotificationImportance.Low);
                    notificationManager.CreateNotificationChannel(_notificationChannel);
                }
                builder.SetChannelId(_notificationChannel.Id);
            }

            if (/*Build.VERSION.SdkInt <= BuildVersionCodes.N && */ _appSettings.AutofillPersistNotification)
            {
                builder.SetPriority(-2);
            }

            _lastNotificationTime = now;
            _lastNotificationUri  = uri;
            notificationManager.Notify(AutoFillNotificationId, builder.Build());

            builder.Dispose();
        }
        /// <summary>
        /// Show a local notification
        /// </summary>
        /// <param name="title">Title of the notification</param>
        /// <param name="body">Body or description of the notification</param>
        /// <param name="id">Id of the notification</param>
        public void Show(string title, string body, int id = 0)
        {
            var builder = new Notification.Builder(Application.Context);

            //var builder = new NotificationCompat.Builder(Application.Context);

            builder.SetContentTitle(title);
            builder.SetContentText(body);
            builder.SetAutoCancel(true);
            builder.SetPriority(Priority);
            builder.SetVibrate(Vibrate);


            if (NotificationIconId != 0)
            {
                builder.SetSmallIcon(NotificationIconId);
            }
            else
            {
                builder.SetSmallIcon(Resource.Drawable.plugin_lc_smallicon);
            }

            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                var channelId = $"{_packageName}.general";
                //var channel = new NotificationChannel(channelId, "General", NotificationImportance.Default);
                var channel = new NotificationChannel(channelId, "General", Importance);

                _manager.CreateNotificationChannel(channel);

                builder.SetChannelId(channelId);
            }

            var resultIntent = GetLauncherActivity();

            resultIntent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);
            var stackBuilder = Android.Support.V4.App.TaskStackBuilder.Create(Application.Context);

            stackBuilder.AddNextIntent(resultIntent);
            var resultPendingIntent =
                stackBuilder.GetPendingIntent(0, (int)PendingIntentFlags.UpdateCurrent);

            builder.SetContentIntent(resultPendingIntent);

            _manager.Notify(id, builder.Build());
        }
        /// <summary>
        /// Отображает новое уведомление в строке состояния Android.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="notification"></param>
        private void ShowNotification(Context context, Lers.Notification notification)
        {
            // https://forums.xamarin.com/discussion/69009/notification-click-to-run-activity

            // По взаимодействию с формами.
            // https://stackoverflow.com/questions/34754149/android-xamarin-make-push-notification-not-create-a-new-activity-but-use-the-cur

            var valuesForActivity = new Bundle();

            valuesForActivity.PutInt("NotificationId", notification.Id);

            var resultIntent = new Intent(context, typeof(MainActivity));

            // Устанавливаем параметр "Идентификатор" для уведомление
            resultIntent.PutExtras(valuesForActivity);

            var stackBuilder = TaskStackBuilder.Create(context);

            // Указываем стартовую активность - Главная форма
            stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(MainActivity)));
            stackBuilder.AddNextIntent(resultIntent);

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

            int iconImportance = ResourceUtils.GetImageByImportance(notification.Importance);

            var notificationBuilder = new Notification.Builder(context)
                                      .SetAutoCancel(true)
                                      .SetSmallIcon(iconImportance)
                                      .SetContentTitle(notification.Type.GetDescription())
                                      .SetContentText(notification.Message)
                                      .SetStyle(new Notification.BigTextStyle())
                                      .SetContentIntent(pendingIntent);

            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                // Каналы поддерживаются только на OREO и выше.
                notificationBuilder.SetChannelId(Channels.GeneralChannelId);
            }

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

            notificationManager.Notify(notification.Id, notificationBuilder.Build());
        }
Beispiel #10
0
        public static void Notify(LocalNotification notification)
        {
            var builder = new Notification.Builder(Application.Context);

            builder.SetContentTitle(notification.Title);
            builder.SetContentText(notification.Body);
            builder.SetAutoCancel(true);
            builder.SetPriority((int)NotificationPriority.Max);
            builder.SetSmallIcon(notification.IconId);

            // Tapping on the notification
            var defaultAction = notification.Actions.FirstOrDefault(a => a.ActionId == ActionIdentifiers.Default);

            builder.SetContentIntent(CreateActivityPendingIntent(notification.Id, defaultAction));

            // Dismissing a notification (swiping the notification)
            var dismissAction = notification.Actions.FirstOrDefault(a => a.ActionId == ActionIdentifiers.Dismiss);

            if (dismissAction != null)
            {
                builder.SetDeleteIntent(CreatePendingIntent(notification.Id, dismissAction));
            }

            // User actions
            var actions = notification.Actions.Where(a => a.ActionId == ActionIdentifiers.Action).ToArray();

            if (actions.Any())
            {
                builder.SetActions(GetNotificationActions(notification, actions).ToArray());
            }

            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                var channelId = $"{Application.Context.PackageName}.general";
                var channel   = new NotificationChannel(channelId, "General", NotificationImportance.Max);

                _manager.CreateNotificationChannel(channel);

                builder.SetChannelId(channelId);
            }

            _manager.Notify(notification.Id, builder.Build());
        }
    //protected override void OnError(Context context, string errorId)
    //{
    //    Log.Error(ApplicationSettings.AzureTag, "GCM Error: " + errorId);
    //}

    //  protected override void OnRegistered(Context context, string registrationId)
    //  {
    //PushNotificationImplementation.registerRequest.deviceToken = registrationId;
    //ApplicationSettings.DeviceToken = registrationId;

    ////added on 1/25/17 by aditmer to unregister the device if the registrationId has changed
    //CheckInstallationID.CheckNewInstallationID(registrationId);

    //Webservices.RegisterPush(PushNotificationImplementation.registerRequest);
    ////commented out on 11/29/16 by aditmer so we can register on the server
    //    //RegistrationID = registrationId;

    //    //Hub = new NotificationHub(NightscoutMobileHybrid.Constants.NotificationHubPath, NightscoutMobileHybrid.Constants.ConnectionString, context);

    //    //try
    //    //{
    //    //    Hub.UnregisterAll(registrationId);
    //    //}
    //    //catch (Exception ex)
    //    //{
    //    //    Log.Error(ApplicationSettings.AzureTag, ex.Message);
    //    //}


    //    //var tags = new List<string>() { ApplicationSettings.AzureTag };

    //    //try
    //    //{
    //    //    const string templateBodyGCM = "{\"data\":{\"message\":\"$(message)\",\"eventName\":\"$(eventName)\",\"group\":\"$(group)\",\"key\":\"$(key)\",\"level\":\"$(level)\",\"sound\":\"$(sound)\",\"title\":\"$(title)\"}}";

    //    //    var hubRegistration = Hub.RegisterTemplate(registrationId, "nightscout", templateBodyGCM, tags.ToArray());
    //    //}
    //    //catch (Exception ex)
    //    //{
    //    //    Log.Error(ApplicationSettings.AzureTag, ex.Message);
    //    //}
    //}

    //protected override void OnUnRegistered(Context context, string registrationId)
    //{
    //    createNotification("0", "GCM Unregistered...", "The device has been unregistered!", 0,"0","0");
    //}

    void createNotification(string key, string title, string desc, int sound, string group, string level)
    {
        var intent = new Intent(this, typeof(MainActivity));

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

        //addd on 12/5/16 by aditmer to add actions to the push notifications

        AckRequest ack = new AckRequest();

        ack.group = group;
        ack.key   = key;
        ack.level = level;
        ack.time  = ApplicationSettings.AlarmUrgentMins1;
        var notificationIntent = new Intent(this, typeof(NotificationActionService));

        notificationIntent.PutExtra("ack", JsonConvert.SerializeObject(ack));
        var snoozeIntent1 = PendingIntent.GetService(this, 0, notificationIntent, PendingIntentFlags.OneShot);

        //adds 2nd action that snoozes the alarm for the ApplicationSettings.AlarmUrgentMins[1] amount of time
        var        notificationIntent2 = new Intent(this, typeof(NotificationActionService));
        AckRequest ack2 = new AckRequest();

        ack2.group = group;
        ack2.key   = key;
        ack2.level = level;
        ack2.time  = ApplicationSettings.AlarmUrgentMins2;
        notificationIntent2.PutExtra("ack", JsonConvert.SerializeObject(ack2));
        var snoozeIntent2 = PendingIntent.GetService(this, 0, notificationIntent2, PendingIntentFlags.OneShot);

        //Notification.Action notificationAction = new Notification.Action(0, "Snooze", snoozeIntent);


        var notificationBuilder = new Notification.Builder(this);

        if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
        {
            notificationBuilder.SetChannelId("nightscout");
        }
        notificationBuilder.SetSmallIcon(NightscoutMobileHybrid.Droid.Resource.Drawable.icon);
        notificationBuilder.SetContentTitle(title);
        notificationBuilder.SetContentText(desc);
        notificationBuilder.SetAutoCancel(true);
        notificationBuilder.SetPriority((int)NotificationPriority.Max);
        notificationBuilder.SetContentIntent(pendingIntent);

        notificationBuilder.AddAction(0, $"Snooze {ack.time} min", snoozeIntent1);
        notificationBuilder.AddAction(0, $"Snooze {ack2.time} min", snoozeIntent2);

        if (sound == 0)
        {
            notificationBuilder.SetDefaults(NotificationDefaults.Vibrate | NotificationDefaults.Lights | NotificationDefaults.Sound);
        }
        else
        {
            notificationBuilder.SetDefaults(NotificationDefaults.Vibrate | NotificationDefaults.Lights);
            notificationBuilder.SetSound(Android.Net.Uri.Parse(ContentResolver.SchemeAndroidResource + "://" + PackageName + "/Raw/" + sound));
        }

        var notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);
        var notification        = notificationBuilder.Build();

        if (sound != 0)
        {
            notification.Flags = NotificationFlags.Insistent;
        }
        notificationManager.Notify(key, 1, notification);

        //Not using in-app notifications (Nightscout handles all of that for us)
        //dialogNotify(title, desc);
    }
        private void CreateBuilder()
        {
            var builder = new Notification.Builder(Application.Context, channelId);

            builder.SetChannelId(channelId);

            //Configure builder
            builder.SetContentTitle("track title goes here");
            builder.SetContentText("artist goes here");
            builder.SetWhen(0);

            //TODO: set if the notification can be destroyed by swiping
            //if (infos.dismissable)
            //{
            //	builder.setOngoing(false);
            //	Intent dismissIntent = new Intent("music-controls-destroy");
            //	PendingIntent dismissPendingIntent = PendingIntent.getBroadcast(context, 1, dismissIntent, 0);
            //	builder.setDeleteIntent(dismissPendingIntent);
            //}
            //else
            //{
            //	builder.setOngoing(true);
            //}
            if (AndroidMediaManager.SharedInstance.IsPlaying)
            {
                builder.SetOngoing(true);
            }
            else
            {
                builder.SetOngoing(false);
            }

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

            //Set SmallIcon (Notification Icon in top bar)
            builder.SetSmallIcon(Android.Resource.Drawable.IcMediaPlay);

            //TODO: Set LargeIcon
            // builder.SetLargeIcon(AlbumArt.jpg);

            //TODO: Open app if tapped
            //Intent resultIntent = new Intent(context, typeof(Application));
            //resultIntent.SetAction(Intent.ActionMain);
            //resultIntent.AddCategory(Intent.CategoryLauncher);
            //PendingIntent resultPendingIntent = PendingIntent.GetActivity(context, 0, resultIntent, 0);
            //builder.SetContentIntent(resultPendingIntent);

            //Controls
            var controlsCount = 0;

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

            /* Play/Pause */
            if (AndroidMediaManager.SharedInstance.IsPlaying)
            {
                controlsCount++;
                builder.AddAction(pauseAction);
            }
            else
            {
                controlsCount++;
                builder.AddAction(playAction);
            }

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

            this.notificationBuilder = builder;
        }
        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;
        }
Beispiel #14
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 { }
        }
        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);
        }