Пример #1
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());
        }
Пример #2
0
        /// <summary>
        /// Updates the foreground service notification builder, so that it reflects the enrollment status and participation level of the user.
        /// </summary>
        public void UpdateForegroundServiceNotificationBuilder()
        {
            SensusServiceHelper serviceHelper = SensusServiceHelper.Get();

            // the service helper will be null when this method is called from OnCreate. set some generic text until
            // the service helper has a chance to load, at which time this method will be called again and we'll update
            // the notification with more detailed information.
            if (serviceHelper == null)
            {
                _foregroundServiceNotificationBuilder.SetContentTitle("Starting...");
                _foregroundServiceNotificationBuilder.SetContentText("Tap to Open Sensus.");
            }
            // after the service helper has been initialized, we'll have more information about the studies.
            else
            {
                int numRunningStudies = serviceHelper.RegisteredProtocols.Count(protocol => protocol.State == ProtocolState.Running);

                _foregroundServiceNotificationBuilder.SetContentTitle("You are participating in " + numRunningStudies + " " + (numRunningStudies == 1 ? "study" : "studies") + ".");

                string contentText = "";

                // although the number of studies might be greater than 0, the protocols might not yet be started (e.g., after starting sensus).
                // also, only display the percentage if at least one protocol is configured to display it.
                List <Protocol> protocolsToAverageParticipation = serviceHelper.GetRunningProtocols()
                                                                  .Where(runningProtocol => runningProtocol.DisplayParticipationPercentageInForegroundServiceNotification).ToList();
                if (protocolsToAverageParticipation.Count > 0)
                {
                    double avgParticipation = protocolsToAverageParticipation.Average(protocol => protocol.Participation) * 100;
                    contentText += "Your overall participation level is " + Math.Round(avgParticipation, 0) + "%. ";
                }

                contentText += "Tap to open Sensus.";

                _foregroundServiceNotificationBuilder.SetContentText(contentText);

                // allow user to pause/resume data collection via the notification
                if (Build.VERSION.SdkInt >= BuildVersionCodes.N)
                {
                    // clear current actions
                    _foregroundServiceNotificationBuilder.SetActions();

                    // add pause action
                    int numPausableProtocols = serviceHelper.RegisteredProtocols.Count(protocol => protocol.State == ProtocolState.Running && protocol.AllowPause);
                    if (numPausableProtocols > 0)
                    {
                        Intent        pauseActionIntent        = new Intent(FOREGROUND_SERVICE_NOTIFICATION_ACTION_PAUSE);
                        PendingIntent pauseActionPendingIntent = PendingIntent.GetBroadcast(Application.Context, 0, pauseActionIntent, PendingIntentFlags.CancelCurrent);
                        string        pauseActionTitle         = "Pause " + numPausableProtocols + " " + (numPausableProtocols == 1 ? "study" : "studies") + ".";
                        _foregroundServiceNotificationBuilder.AddAction(new Notification.Action(Resource.Drawable.ic_media_pause_light, pauseActionTitle, pauseActionPendingIntent));  // note that notification actions no longer display the icon
                    }

                    // add resume action
                    int numPausedStudies = serviceHelper.RegisteredProtocols.Count(protocol => protocol.State == ProtocolState.Paused);
                    if (numPausedStudies > 0)
                    {
                        Intent        resumeActionIntent        = new Intent(FOREGROUND_SERVICE_NOTIFICATION_ACTION_RESUME);
                        PendingIntent resumeActionPendingIntent = PendingIntent.GetBroadcast(Application.Context, 0, resumeActionIntent, PendingIntentFlags.CancelCurrent);
                        string        resumeActionTitle         = "Resume " + numPausedStudies + " " + (numPausedStudies == 1 ? "study" : "studies") + ".";
                        _foregroundServiceNotificationBuilder.AddAction(new Notification.Action(Resource.Drawable.ic_media_play_light, resumeActionTitle, resumeActionPendingIntent));  // note that notification actions no longer display the icon
                    }
                }
            }
        }
Пример #3
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 { }
        }