Exemplo n.º 1
0
        public void SendDumbNotification()
        {
            Notification.Builder builder;
            if (Build.VERSION.SdkInt < BuildVersionCodes.NMr1)
            {
#pragma warning disable CS0618 // 'Notification.Builder.SetPriority(int)' está obsoleto: 'deprecated'

                builder = new Notification.Builder(Application.Context);
                builder.SetPriority(Convert.ToInt32(NotificationPriority.Max));
#pragma warning restore CS0618 // 'Notification.Builder.SetPriority(int)' está obsoleto: 'deprecated'
            }
            else
            {
                NotificationChannel notificationChannel = new NotificationChannel("livedisplaynotificationchannel", "LiveDisplay", NotificationImportance.Max);
                notificationManager.CreateNotificationChannel(notificationChannel);
                builder = new Notification.Builder(Application.Context, "livedisplaynotificationchannel");
            }
#pragma warning restore
            builder.SetContentTitle("");
            builder.SetContentText("");
            builder.SetAutoCancel(true);

            builder.SetSmallIcon(Resource.Drawable.ic_stat_default_appicon);
            notificationManager.Notify(2, 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);
        }
Exemplo n.º 3
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();
        }
Exemplo n.º 4
0
        //used to generate local notifications
        public void CreateNotification(dynamic response)
        {
            TaskStackBuilder stackBuilder = TaskStackBuilder.Create(this);
            Intent           wklIntent    = new Intent(this, typeof(WorkListActivity));

            stackBuilder.AddNextIntent(wklIntent);

            PendingIntent pendingIntent = stackBuilder.GetPendingIntent(0, PendingIntentFlags.OneShot);  //id=0

            Notification.Style style;
            if (response.Count == 1)
            {
                Notification.BigTextStyle textStyle = new Notification.BigTextStyle();
                textStyle.BigText(response[0]["MSG_CONTENT"]);
                textStyle.SetSummaryText(response[0]["MSG_TITLE"]);
                style = textStyle;
            }
            else
            {
                Notification.InboxStyle inboxStyle = new Notification.InboxStyle();
                inboxStyle.AddLine(response[0]["MSG_CONTENT"]);
                inboxStyle.AddLine(response[1]["MSG_CONTENT"]);
                if (response.Count > 2)
                {
                    inboxStyle.SetSummaryText("+" + (response.Count - 2) + " more");
                }
                style = inboxStyle;
            }

            Notification.Builder builder = new Notification.Builder(Application.Context)
                                           .SetContentTitle("PeoplePlus Notification")
                                           .SetContentText("Pending Tasks in your WorkList Viewer")
                                           .SetSmallIcon(Resource.Drawable.login3)
                                           .SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.login3))
                                           .SetAutoCancel(true)
                                           .SetContentIntent(pendingIntent);

            if ((int)Build.VERSION.SdkInt >= 21)
            {
                builder.SetVisibility(NotificationVisibility.Private)
                .SetCategory(Notification.CategoryAlarm)
                .SetCategory(Notification.CategoryCall)
                .SetStyle(style);
            }

            builder.SetPriority((int)NotificationPriority.High);
            builder.SetDefaults(NotificationDefaults.Sound | NotificationDefaults.Vibrate);

            Notification notification = builder.Build();

            NotificationManager notificationManager = GetSystemService(NotificationService) as NotificationManager;

            notificationManager.Notify(0, notification);
        }
Exemplo n.º 5
0
        private void CheckServerNotifications(Context pContext, string sClan, string sName)
        {
            XElement pResponse = null;
            //try
            //{
            string sPrevClan = Master.GetActiveClan();
            string sPrevUser = Master.GetActiveUserName();

            Master.SetActiveClan(sClan);
            Master.SetActiveUserName(sName);
            string sResponse = WebCommunications.SendPostRequest(Master.GetBaseURL() + Master.GetServerURL() + "GetUnseenNotifications", Master.BuildCommonBody(), true);

            pResponse = Master.ReadResponse(sResponse);
            Master.SetActiveClan(sPrevClan);
            Master.SetActiveUserName(sPrevUser);
            //}
            //catch (Exception e) { return; }

            if (pResponse.Element("Data") != null && pResponse.Element("Data").Element("Notifications").Value != "")
            {
                List <XElement> pNotifications = pResponse.Element("Data").Element("Notifications").Elements("Notification").ToList();
                foreach (XElement pNotification in pNotifications)
                {
                    string sContent  = pNotification.Value;
                    string sGameID   = pNotification.Attribute("GameID").Value;
                    string sGameName = pNotification.Attribute("GameName").Value;

                    Notification.Builder pBuilder = new Notification.Builder(pContext);
                    pBuilder.SetContentTitle(sClan + " - " + sGameName);
                    pBuilder.SetContentText(sContent);
                    pBuilder.SetSmallIcon(Resource.Drawable.Icon);
                    pBuilder.SetVibrate(new long[] { 200, 50, 200, 50 });
                    pBuilder.SetVisibility(NotificationVisibility.Public);
                    pBuilder.SetPriority((int)NotificationPriority.Default);

                    Intent pIntent = null;
                    if (sGameID.Contains("Zendo"))
                    {
                        pIntent = new Intent(pContext, typeof(ZendoActivity));
                    }
                    pIntent.SetAction(sGameID);
                    pIntent.PutExtra("GameName", sGameName);

                    pBuilder.SetContentIntent(PendingIntent.GetActivity(pContext, 0, pIntent, 0));
                    pBuilder.SetStyle(new Notification.BigTextStyle().BigText(sContent));

                    Notification        pNotif   = pBuilder.Build();
                    NotificationManager pManager = (NotificationManager)pContext.GetSystemService(Context.NotificationService);
                    pManager.Notify((int)Java.Lang.JavaSystem.CurrentTimeMillis(), pNotif);                     // using time to make different ID every time, so doesn't replace old notification
                    //pManager.Notify(DateTime.Now.Millisecond, pNotif); // using time to make different ID every time, so doesn't replace old notification
                }
            }
        }
Exemplo n.º 6
0
        public void PostNotification(string title, string text, bool autoCancellable, NotificationPriority notificationPriority)
        {
#pragma warning disable CS0618 // 'Notification.Builder(Context) está obsoleto
            Notification.Builder builder = new Notification.Builder(Application.Context);
#pragma warning restore
            builder.SetContentTitle(title);
            builder.SetContentText(text);
            builder.SetAutoCancel(autoCancellable);
#pragma warning disable CS0618 // 'Notification.Builder.SetPriority(int)' está obsoleto: 'deprecated'
            builder.SetPriority(Convert.ToInt32(NotificationPriority.Low));
#pragma warning restore CS0618 // 'Notification.Builder.SetPriority(int)' está obsoleto: 'deprecated'

            builder.SetSmallIcon(Resource.Drawable.ic_stat_default_appicon);
            notificationManager.Notify(1, builder.Build());
        }
Exemplo n.º 7
0
 void CreateNotification(PushNoticationMessage pushMessage)
 {
     try
     {
         // Get the notifications manager:
         NotificationManager notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
         // Instantiate the notification builder:
         //TODO: Get the Name of  the App from Manifest
         Notification.Builder builder = new Notification.Builder(this)
                                        .SetContentTitle("Quick Task")
                                        .SetContentText(pushMessage.Title)
                                        .SetAutoCancel(true)
                                        .SetSmallIcon(Resource.Drawable.icon)
                                        .SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.icon));
         builder.SetVisibility(NotificationVisibility.Public);
         builder.SetPriority((int)NotificationPriority.High);
         builder.SetCategory(Notification.CategoryMessage);
         //Setup an intent for the Main Activity:
         Intent secondIntent = new Intent(this, typeof(MainActivity));
         secondIntent.PutExtra("recdMessage", Settings.Current.LastMessage);
         // Pressing the Back button in SecondActivity exits the app:
         Android.App.TaskStackBuilder stackBuilder = Android.App.TaskStackBuilder.Create(this);
         // Add the back stack for the intent:
         stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(MainActivity)));
         // 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);
         builder.SetContentIntent(pendingIntent);
         // Build the notification:
         Notification notification = builder.Build();
         notification.Defaults |= NotificationDefaults.Sound;
         // 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 = 6;
         // Launch notification:
         notificationManager.Notify(notificationId, notification);
         Log.Info(AppConstants.TAG, "Local Notification Sent");
     }
     catch (Exception ex)
     {
         Log.Info(AppConstants.TAG, "Local Notify Failed with " + ex.Message);
     }
 }
Exemplo n.º 8
0
 private void InitNotification()
 {
     if (mNotificationBuilder == null)
     {
         mNotificationBuilder = new Notification.Builder(this);
         mNotificationBuilder.SetSmallIcon(Resource.Drawable.Ares);
         mNotificationBuilder.SetOngoing(true);
         TaskStackBuilder stackBuilder = TaskStackBuilder.Create(this);
         stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(MainActivity)));
         Intent resultIntent = new Intent(this, typeof(MainActivity));
         stackBuilder.AddNextIntent(resultIntent);
         PendingIntent resultPendingIntent = stackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent);
         mNotificationBuilder.SetContentIntent(resultPendingIntent);
         mNotificationBuilder.SetPriority((int)NotificationPriority.Low);
     }
 }
        /// <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());
        }
Exemplo n.º 10
0
        void CreateNotification(PushNoticationMessage pushedMessage)
        {
            // Get the notifications manager:
            NotificationManager notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;

            // Instantiate the notification builder:
            Notification.Builder builder = new Notification.Builder(this)
                                           .SetContentTitle("WK Authenticator")
                                           .SetContentText(pushedMessage.Title)
                                           .SetAutoCancel(true)
                                           .SetSmallIcon(Resource.Drawable.icon)
                                           .SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.icon));
            builder.SetVisibility(NotificationVisibility.Public);
            builder.SetPriority((int)NotificationPriority.High);
            builder.SetCategory(Notification.CategoryMessage);
            //Add Message Information to the Main Activity Intent - This will be shown on Tap Of the Notified Message
            Intent secondIntent = new Intent(this, typeof(MainActivity));

            // Pass the current notification string value to SecondActivity
            secondIntent.PutExtra("recdMessage", Common.Helpers.Settings.LastMessage);
            // Pressing the Back button in SecondActivity exits the app:
            Android.App.TaskStackBuilder stackBuilder = Android.App.TaskStackBuilder.Create(this);
            // Add the back stack for the intent:
            stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(MainActivity)));
            // 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);

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

            notification.Defaults |= NotificationDefaults.Sound;
            // 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 = 0;

            // Launch notification:
            notificationManager.Notify(notificationId, notification);
        }
Exemplo n.º 11
0
    public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
    {
        new Task(() => {
            PendingIntent pIntent        = PendingIntent.GetActivity(this, 0, intent, 0);
            Notification.Builder builder = new Notification.Builder(this);
            builder.SetContentTitle("hello");
            builder.SetContentText("hello");
            builder.SetSmallIcon(Resource.Drawable.Icon);
            builder.SetPriority(1);
            builder.SetDefaults(NotificationDefaults.Sound | NotificationDefaults.Vibrate);
            builder.SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis());
            Notification notifikace = builder.Build();
            NotificationManager notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
            const int notificationId = 0;
            notificationManager.Notify(notificationId, notifikace);
        }).Start();

        return(StartCommandResult.Sticky);
    }
Exemplo n.º 12
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());
        }
Exemplo n.º 13
0
        public static void SendDumbNotification()
        {
            NotificationManager notificationManager = (NotificationManager)Application.Context.GetSystemService("notification");

            Notification.Builder builder;
            if (Build.VERSION.SdkInt < BuildVersionCodes.NMr1)
            {
#pragma warning disable CS0618 // 'Notification.Builder.SetPriority(int)' está obsoleto: 'deprecated'

                builder = new Notification.Builder(Application.Context);
                builder.SetPriority(Convert.ToInt32(NotificationPriority.Max));
#pragma warning restore CS0618 // 'Notification.Builder.SetPriority(int)' está obsoleto: 'deprecated'
            }
            else
            {
                NotificationChannel notificationChannel = new NotificationChannel("livedisplaynotificationchannel", "LiveDisplay", NotificationImportance.Max);
                notificationManager.CreateNotificationChannel(notificationChannel);
                builder = new Notification.Builder(Application.Context, "livedisplaynotificationchannel");
            }

            RemoteInput remoteInput = new RemoteInput.Builder("test1").SetLabel("This is the place where you write").Build();

            Intent intent = new Intent(Application.Context, Java.Lang.Class.FromType(typeof(MainActivity)));

            PendingIntent pendingIntent = PendingIntent.GetActivity(Application.Context, 35, intent, PendingIntentFlags.UpdateCurrent);

            Notification.Action.Builder action = new Notification.Action.Builder(Resource.Drawable.ic_stat_default_appicon, "Answer", pendingIntent).AddRemoteInput(remoteInput);

            builder.SetStyle(new Notification.MessagingStyle("Su madre").AddMessage(new Notification.MessagingStyle.Message("hi", -1, "user1"))
                             .AddMessage(new Notification.MessagingStyle.Message("WhatsUp", 0, "user2"))
                             .AddMessage(new Notification.MessagingStyle.Message("How bout lunch?", 1, "user1")));
#pragma warning restore
            builder.SetContentTitle("");
            builder.SetContentText("");
            builder.SetAutoCancel(true);
            builder.AddAction(action.Build());

            builder.SetSmallIcon(Resource.Drawable.ic_stat_default_appicon);
            notificationManager.Notify(2, builder.Build());
        }
Exemplo n.º 14
0
        private void BtnNotify_Click(object sender, EventArgs e)
        {
            //Intent intent = new Intent(this, typeof(MainActivity));
            //const int pendingIntentId = 0;
            //PendingIntent pendingIntent =
            //    PendingIntent.GetActivity(this, pendingIntentId, intent, PendingIntentFlags.OneShot);

            Notification.Builder builder = new Notification.Builder(this);
            //builder.SetContentIntent(pendingIntent);
            builder.SetPriority((int)NotificationPriority.High);
            builder.SetContentTitle("알려드립니다!!");
            builder.SetContentText("Hello World! This is my first notification!");
            builder.SetDefaults(NotificationDefaults.Sound | NotificationDefaults.Vibrate | NotificationDefaults.Lights);
            builder.SetSmallIcon(Resource.Drawable.Icon);
            Notification noti = builder.Build();

            // Build the notification:
            Notification        notification = builder.Build();
            NotificationManager manager      = GetSystemService(Context.NotificationService) as NotificationManager;

            manager.Notify(101, noti);
        }
Exemplo n.º 15
0
        /*
         * Create builder and assign title and text to the notification
         */
        public Notification.Builder CreateNotificationBuilder(string title, string content)
        {
            Notification.Builder builder = null;

            //if version is lower than Android O, priority has to be set manually
            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
            {
                builder = new Notification.Builder(CrossCurrentActivity.Current.Activity.ApplicationContext, "Location-based information");
            }
            else
            {
                builder = new Notification.Builder(CrossCurrentActivity.Current.Activity.ApplicationContext, "Location-based information");
                int priority = (int)NotificationPriority.High;
                builder.SetPriority(priority);
            }
            var context = CrossCurrentActivity.Current.AppContext;

            builder.SetContentTitle(title);
            builder.SetContentText(content);
            builder.SetSmallIcon(Resource.Drawable.Notification_Icon);
            return(builder);
        }
Exemplo n.º 16
0
        //used to generate local notifications for remote messages
        void SendNotification(Dictionary <string, string> response)
        {
            TaskStackBuilder stackBuilder = TaskStackBuilder.Create(this);
            Intent           wklIntent    = new Intent(this, typeof(WorkListActivity));

            stackBuilder.AddNextIntent(wklIntent);

            PendingIntent pendingIntent = stackBuilder.GetPendingIntent(0, PendingIntentFlags.OneShot);  //id=0

            Notification.BigTextStyle style = new Notification.BigTextStyle();
            style.BigText(response["MSG_CONTENT"]);
            style.SetSummaryText(response["MSG_TITLE"]);

            Notification.Builder builder = new Notification.Builder(Application.Context)
                                           .SetContentTitle("PeoplePlus Notification")
                                           .SetContentText("Pending Task(s) in your WorkList Viewer")
                                           .SetSmallIcon(Resource.Drawable.neptunelogo)
                                           .SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.neptunelogo))
                                           .SetAutoCancel(true)
                                           .SetContentIntent(pendingIntent);

            if ((int)Build.VERSION.SdkInt >= 21)
            {
                builder.SetVisibility(NotificationVisibility.Private)
                .SetCategory(Notification.CategoryAlarm)
                .SetCategory(Notification.CategoryCall)
                .SetStyle(style);
            }

            builder.SetPriority((int)NotificationPriority.High);
            builder.SetDefaults(NotificationDefaults.Sound | NotificationDefaults.Vibrate);

            Notification notification = builder.Build();

            NotificationManager notificationManager = GetSystemService(NotificationService) as NotificationManager;

            notificationManager.Notify(0, notification);
        }
        private void SetMetadata(Notification.Builder builder)
        {
            if ((int)Build.VERSION.SdkInt >= 16)
            {
                builder.SetPriority(highPriority.Checked ? (int)NotificationPriority.High : (int)NotificationPriority.Default);
            }

            if ((int)Build.VERSION.SdkInt >= (int)BuildVersionCodes.Lollipop)
            {
                builder.SetCategory(Notification.CategoryMessage);
                var visibility = NotificationVisibility.Public;
                if (spinner.SelectedItemPosition == 1)
                {
                    visibility = NotificationVisibility.Private;
                }
                else if (spinner.SelectedItemPosition == 2)
                {
                    visibility = NotificationVisibility.Secret;
                }

                builder.SetVisibility(visibility);
            }
        }
    //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);
    }
Exemplo n.º 19
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);
            };
        }
Exemplo n.º 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
        }
Exemplo n.º 21
0
        public void Show(int id, string title, string body, SoundType?soundType)
        {
            var    appIcon = BitmapFactory.DecodeResource(Application.Context.Resources, Resource.Drawable.appIcon);
            Bitmap bm      = Bitmap.CreateScaledBitmap(appIcon,
                                                       48,
                                                       48,
                                                       true);
            bool hasSound      = soundType.HasValue;
            var  soundProvider = Xamarin.Forms.DependencyService.Get <INotificationSoundProvider>();

            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                var generalChannel = new NotificationChannel(GeneralChannelId, "Notifications", NotificationImportance.Default)
                {
                    LightColor  = Resource.Color.colorAccent,
                    Description = "App notifications with sound"
                };
                var lowChannel = new NotificationChannel(LowChannelId, "General", NotificationImportance.Low)
                {
                    LightColor  = Resource.Color.colorAccent,
                    Description = "App notifications without sound",
                };

                generalChannel.EnableLights(true);
                lowChannel.EnableLights(true);
                lowChannel.SetSound(null, null);

                NotifManager.CreateNotificationChannel(generalChannel);
                NotifManager.CreateNotificationChannel(lowChannel);

                // play sound
                if (hasSound)
                {
                    soundProvider.Play(soundType.Value);
                }
            }

            var soundUri = hasSound
                ? Android.Net.Uri.Parse(soundProvider.GetSoundPath(soundType.Value))
                : RingtoneManager.GetDefaultUri(RingtoneType.Notification);

            var audioAttributes = new AudioAttributes.Builder()
                                  .SetContentType(AudioContentType.Sonification)
                                  .SetUsage(AudioUsageKind.Alarm)
                                  .SetLegacyStreamType(Stream.Alarm)
                                  .Build();

            //we use the main because we dont want to show the splash again..
            //and because the splash produces a bug where the timer gets paused xd
            var resultIntent = new Intent(Application.Context, typeof(MainActivity));
            //resultIntent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTop | ActivityFlags.SingleTop);
            //resultIntent.SetAction(Intent.ActionMain);
            //resultIntent.AddCategory(Intent.CategoryLauncher);
            //resultIntent.SetFlags(ActivityFlags.SingleTop);
            //resultIntent.SetFlags(ActivityFlags.NewTask);

            //var pendingIntent = PendingIntent.GetActivity(Application.Context, 1, resultIntent, PendingIntentFlags.UpdateCurrent);
            var bundle = new Bundle();

            bundle.PutString(nameof(NotificationService), $"{id}");
            var pendingIntent = Android.Support.V4.App.TaskStackBuilder.Create(Application.Context)
                                .AddNextIntent(resultIntent)
                                .GetPendingIntent(1, (int)PendingIntentFlags.UpdateCurrent, bundle);

            string channelId = hasSound ? LowChannelId : GeneralChannelId;
            var    builder   = new Notification.Builder(Application.Context, channelId)
                               .SetContentTitle(title)
                               .SetContentText(body)
                               .SetAutoCancel(true)
                               .SetSmallIcon(Resource.Drawable.appIcon)
                               .SetColor(Color.Red.ToArgb())
                               .SetLargeIcon(bm)
                               .SetContentIntent(pendingIntent);

            if (hasSound &&
                Build.VERSION.SdkInt < BuildVersionCodes.O)
            {
                //This are deprecated for android O +
#pragma warning disable CS0618 // Type or member is obsolete
                builder.SetSound(soundUri, audioAttributes);
                builder.SetPriority(NotificationCompat.PriorityDefault);
#pragma warning restore CS0618 // Type or member is obsolete
            }
            var notification = builder.Build();

            NotifManager.Notify(id, notification);
        }