コード例 #1
0
        public void DisplayNotificationIfNextGameIsToday(IList <Fixture> fixtures)
        {
            //var now = new DateTime(2014, 9, 14, 15, 00, 00);
            var now                 = DateTime.Now;
            var fixture             = fixtures[0];
            var notificationManager = (NotificationManager)_context.GetSystemService(Context.NOTIFICATION_SERVICE);

            if (fixture.Date.Date == now.Date && now <= fixture.Date)
            {
                var bigText = new Notification.BigTextStyle();
                bigText.BigText(fixture.HomeTeam + " v " + fixture.AwayTeam);

                var footballTodayMessage = "Football today at " + fixture.Date.ToString("HH:mm");

                bigText.SetBigContentTitle(footballTodayMessage);

                var notification = new Notification.Builder(_context)
                                   .SetSmallIcon(R.Drawables.Icon)
                                   .SetStyle(bigText)
                                   .SetTicker(footballTodayMessage)
                                   .Build();

                notificationManager.Notify(1, notification);
            }
            else
            {
                notificationManager.CancelAll();
            }
        }
コード例 #2
0
        public static void ShowNotification(Context context, string contentTitle,
                                            string contentText)
        {
            var intent =
                context.PackageManager.GetLaunchIntentForPackage(context.PackageName);

            intent.AddFlags(ActivityFlags.ClearTop);

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

            Notification.BigTextStyle textStyle = new Notification.BigTextStyle();
            textStyle.BigText(contentText);
            textStyle.SetSummaryText("UTDesign Makerspace");

            // Intent
            Notification.Builder builder = new Notification.Builder(context)
                                           .SetContentTitle(contentTitle)
                                           .SetContentText(contentText)
                                           .SetDefaults(NotificationDefaults.Sound | NotificationDefaults.Vibrate)
                                           .SetSmallIcon(Resource.Drawable.icon)
                                           .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification))
                                           .SetContentIntent(pendingIntent)
                                           .SetStyle(textStyle)
                                           .SetPriority(1)
                                           .SetAutoCancel(true);

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

            notificationManager.Notify(1001, builder.Build());
        }
コード例 #3
0
        void SendNotificationEnvioPedido(string message, string trans)
        {
            Log.Debug("Notification", "Chegou aqui notificacao");

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

            intent.PutExtra("notification", "receber_pedido");
            intent.PutExtra("transacao", trans);

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

            var notificationBuilder = new Notification.Builder(this)
                                      .SetSmallIcon(Resource.Drawable.icon)
                                      .SetContentTitle("InBanker")
                                      .SetContentText(message)
                                      .SetAutoCancel(true)
                                      .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification))
                                      .SetContentIntent(pendingIntent);


            Notification.BigTextStyle bigText = new Notification.BigTextStyle();
            bigText.BigText(message);
            notificationBuilder.SetStyle(bigText);

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

            notificationManager.Notify(0, notificationBuilder.Build());
        }
コード例 #4
0
        public void DisplayNotificationIfNextGameIsToday(IList<Fixture> fixtures)
        {
            //var now = new DateTime(2014, 9, 14, 15, 00, 00);
            var now = DateTime.Now;
            var fixture = fixtures[0];
            var notificationManager = (NotificationManager)_context.GetSystemService(Context.NOTIFICATION_SERVICE);

            if (fixture.Date.Date == now.Date && now <= fixture.Date)
            {
                var bigText = new Notification.BigTextStyle();
                bigText.BigText(fixture.HomeTeam + " v " + fixture.AwayTeam);

                var footballTodayMessage = "Football today at " + fixture.Date.ToString("HH:mm");

                bigText.SetBigContentTitle(footballTodayMessage);

                var notification = new Notification.Builder(_context)
                    .SetSmallIcon(R.Drawables.Icon)
                    .SetStyle(bigText)
                    .SetTicker(footballTodayMessage)
                    .Build();

                notificationManager.Notify(1, notification);
            }
            else
            {
                notificationManager.CancelAll();
            }
        }
コード例 #5
0
        private void AdvancedNotificationButton_Click(object sender, EventArgs e)
        {
            Notification.Builder builder = new Notification.Builder(this)
                                           .SetContentTitle("Expanded Layout Notification")
                                           .SetContentText("Learn more about Star Wars")
                                           .SetSmallIcon(Resource.Drawable.notifcation_icon);

            Notification.BigTextStyle textStyle = new Notification.BigTextStyle();

            string longTextMessage = "Lucas ipsum dolor sit amet darth alderaan droid kessel organa jango leia amidala leia aayla. Darth lars sidious grievous. Mara mara wampa skywalker dantooine mon. Watto sith calamari lobot organa qui-gonn alderaan. Boba watto yoda sidious skywalker skywalker ahsoka skywalker.";

            textStyle.BigText(longTextMessage);

            textStyle.SetSummaryText("The Star Wars Ipsum");

            builder.SetStyle(textStyle);

            Notification notification = builder.Build();

            NotificationManager notificationManager = GetSystemService(NotificationService) as NotificationManager;

            const int notificationId = 1;

            notificationManager.Notify(notificationId, notification);
        }
コード例 #6
0
        private void UpdateNotification(bool firstNotification)
        {
            InitNotification();
            mNotificationBuilder.SetContentTitle(Resources.GetString(Resource.String.service_running));
            String secondLine = m_Network != null && m_Network.ClientConnected ?
                                String.Format(Resources.GetString(Resource.String.connected_with), m_Network.ClientName) :
                                Resources.GetString(Resource.String.not_connected);

            mNotificationBuilder.SetContentText(secondLine);
            var    style   = new Notification.BigTextStyle(mNotificationBuilder);
            String project = m_Project != null?
                             String.Format(Resources.GetString(Resource.String.loaded_project), m_Project.Title) :
                                 Resources.GetString(Resource.String.no_project);

            style.BigText(secondLine + "\n" + project);
            mNotificationBuilder.SetStyle(style);
            mNotificationBuilder.SetProgress(0, 0, false);
            if (firstNotification)
            {
                StartForeground(mNotificationId, mNotificationBuilder.Build());
            }
            else
            {
                var nMgr         = (NotificationManager)GetSystemService(NotificationService);
                var notification = mNotificationBuilder.Build();
                notification.Flags |= NotificationFlags.ForegroundService;
                nMgr.Notify(mNotificationId, notification);
            }
        }
コード例 #7
0
        private Notification createNativeNotification(LocalNotification notification)
        {
            var activeContext = Application.Context.ApplicationContext;

            Intent intent = new Intent(activeContext, typeof(MainActivity))
                            .PutExtra(MainActivity.ACTIVITY_NOTIF, notification.Id.ToString());

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

            Notification.BigTextStyle textStyle = new Notification.BigTextStyle();
            textStyle.BigText(notification.Text);
            //textStyle.SetSummaryText("The summary text goes here.");
            var builder = new Notification.Builder(Application.Context)
                          .SetContentIntent(pendingIntent)
                          .SetContentTitle(notification.Title)
                          //.SetContentText(notification.Text)
                          .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification))
                          .SetSmallIcon(Application.Context.ApplicationInfo.Icon)
                          .SetStyle(textStyle);


            var nativeNotification = builder.Build();

            nativeNotification.Flags |= NotificationFlags.AutoCancel;
            return(nativeNotification);
        }
        public override void OnMessageReceived(RemoteMessage message)
        {
            Notification.Builder builder = new Notification.Builder(this)
                                           .SetContentText(message.GetNotification().Body)
                                           .SetSmallIcon(Resource.Drawable.notification)
                                           .SetAutoCancel(true)
                                           .SetVisibility(NotificationVisibility.Public);

            var textStyle = new Notification.BigTextStyle();

            textStyle.BigText(message.GetNotification().Body);
            builder.SetStyle(textStyle);

            Intent        intent          = new Intent(this, typeof(MainActivity));
            const int     pendingIntentId = 0;
            PendingIntent pendingIntent   = PendingIntent.GetActivity(this, pendingIntentId, intent, PendingIntentFlags.OneShot);

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

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

            // Get the notification manager:
            NotificationManager notificationManager =
                GetSystemService(NotificationService) as NotificationManager;

            // Publish the notification:
            const int notificationId = 0;

            notificationManager.Notify(notificationId, notification);
        }
コード例 #9
0
        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);
        }
コード例 #10
0
        public void checkchange()
        {
            while (true)
            {
                IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
                foreach (IPAddress ip in localIPs)
                {
                    if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        if (ipadre != ip.ToString())
                        {
                            servidor.Stop();
                            ipadre = ip.ToString();



                            servidor = new MultitubeWebServer(Android.OS.Environment.ExternalStorageDirectory.ToString(), 12345, ipadre, this);
                            var brandom = new Random();

                            Intent internado2                 = new Intent(this, typeof(serviciointerpreter23));
                            Intent internado3                 = new Intent(this, typeof(serviciointerpreter234));
                            var    pendingIntent3             = PendingIntent.GetService(ApplicationContext, brandom.Next(2000, 50000) + brandom.Next(2000, 50000), internado3, 0);
                            var    pendingIntent2             = PendingIntent.GetService(ApplicationContext, brandom.Next(2000, 50000) + brandom.Next(2000, 50000), internado2, 0);
                            Notification.Action       accion  = new Notification.Action(Resource.Drawable.drwaable, "Parar", pendingIntent2);
                            Notification.Action       accion2 = new Notification.Action(Resource.Drawable.drwaable, "Conectarse", pendingIntent3);
                            Notification.BigTextStyle textoo  = new Notification.BigTextStyle();
                            textoo.SetBigContentTitle("Stremeando en " + ipadre + ":12345");
                            textoo.SetSummaryText("Toque para parar de stremear su media");
                            textoo.BigText("Para conectarse introduzca " + ipadre + ":12345  " + "en su navegador o entre a multitubeweb.tk y toque conectar luego escanee el codigo que aparece al presionar el boton de + en multitubeweb.   al tocar parar se cierrar el servicio de streaming");


#pragma warning disable CS0618 // El tipo o el miembro están obsoletos
                            Notification.Builder nBuilder = new Notification.Builder(this);
#pragma warning restore CS0618 // El tipo o el miembro están obsoletos
                            nBuilder.SetContentTitle("Stremeando en " + ipadre + ":12345");
                            nBuilder.SetContentText("Toque para parar de stremear su media");
                            nBuilder.SetStyle(textoo);
                            nBuilder.SetColor(Android.Graphics.Color.DarkRed.ToArgb());
                            nBuilder.SetOngoing(true);
                            //   nBuilder.SetContentIntent(pendingIntent2);
                            nBuilder.SetSmallIcon(Resource.Drawable.antena);
                            nBuilder.AddAction(accion);
                            nBuilder.AddAction(accion2);
                            Notification notification = nBuilder.Build();
                            StartForeground(193423456, notification);



                            if (CheckInternetConnection() && Constants.UseFirebase)
                            {
                                meterdata();
                            }
                        }
                    }
                }
                MultiHelper.ExecuteGarbageCollection();
                Thread.Sleep(5000);
            }
        }
コード例 #11
0
ファイル: AndroidNotifier.cs プロジェクト: clmckinley/sensus
        public override Task IssueNotificationAsync(string title, string message, string id, bool alertUser, Protocol protocol, int?badgeNumber, NotificationUserResponseAction userResponseAction, string userResponseMessage)
        {
            if (_notificationManager == null)
            {
                return(Task.CompletedTask);
            }
            else if (message == null)
            {
                CancelNotification(id);
            }
            else
            {
                Intent notificationIntent = new Intent(Application.Context, typeof(AndroidMainActivity));
                notificationIntent.PutExtra(NOTIFICATION_USER_RESPONSE_ACTION_KEY, userResponseAction.ToString());
                notificationIntent.PutExtra(NOTIFICATION_USER_RESPONSE_MESSAGE_KEY, userResponseMessage);

                PendingIntent notificationPendingIntent = PendingIntent.GetActivity(Application.Context, 0, notificationIntent, PendingIntentFlags.OneShot);

                SensusNotificationChannel notificationChannel = SensusNotificationChannel.Default;

                if (userResponseAction == NotificationUserResponseAction.DisplayPendingSurveys)
                {
                    notificationChannel = SensusNotificationChannel.Survey;
                }

                // reset channel to silent if we're not notifying/alerting or if we're in an exclusion window
                if (!alertUser || (protocol != null && protocol.TimeIsWithinAlertExclusionWindow(DateTime.Now.TimeOfDay)))
                {
                    notificationChannel = SensusNotificationChannel.Silent;
                }

                Notification.Builder notificationBuilder = CreateNotificationBuilder(notificationChannel)
                                                           .SetContentTitle(title)
                                                           .SetContentText(message)
                                                           .SetSmallIcon(Resource.Drawable.ic_launcher)
                                                           .SetContentIntent(notificationPendingIntent)
                                                           .SetAutoCancel(true)
                                                           .SetOngoing(false);
                if (badgeNumber != null)
                {
                    notificationBuilder.SetNumber(badgeNumber.Value);
                }

                // use big-text style for long messages
                if (message.Length > 20)
                {
                    Notification.BigTextStyle bigTextStyle = new Notification.BigTextStyle();
                    bigTextStyle.BigText(message);
                    notificationBuilder.SetStyle(bigTextStyle);
                }

                _notificationManager.Notify(id, 0, notificationBuilder.Build());
            }

            return(Task.CompletedTask);
        }
コード例 #12
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);
        }
コード例 #13
0
        public Notification.Builder GetNotification(String title, String body)
        {
            Notification.BigTextStyle textStyle = new Notification.BigTextStyle();
            textStyle.BigText(body);

            return(new Notification.Builder(ApplicationContext, PRIMARY_CHANNEL)
                   .SetContentTitle(title)
                   .SetContentText(body)
                   .SetSmallIcon(SmallIcon)
                   .SetAutoCancel(true)
                   .SetStyle(textStyle));
        }
コード例 #14
0
        protected override void OnCreate(Bundle bundle)
        {
            int i = 1;

            base.OnCreate(bundle);
            SetContentView(Resource.Layout.PaymentPage);
            Button paymentbtn = FindViewById <Button>(Resource.Id.paymentbtn);

            paymentbtn.Click += (o, e) =>
            {
                Toast.MakeText(this, "Confirmed", ToastLength.Short).Show();


                Notification.BigTextStyle textStyle = new Notification.BigTextStyle();

                textStyle.BigText("Your Code is 1234");
                // Set the summary text:
                textStyle.SetSummaryText("Enjoy :)");

                var notificationBuilder = new Notification.Builder(this)

                                          .SetContentTitle("Smarty's Notification")
                                          .SetContentText("Body goes here...........This is a big Notificaiton in Notification Tray")
                                          .SetAutoCancel(true)

                                          .SetPriority((int)NotificationPriority.Max)
                                          .SetDefaults(NotificationDefaults.Sound | NotificationDefaults.Vibrate | NotificationDefaults.Lights)
                                          .SetStyle(textStyle);

                if ((int)Android.OS.Build.VERSION.SdkInt >= 21)
                {
                    notificationBuilder.SetVisibility(NotificationVisibility.Public);
                    notificationBuilder.SetCategory(Notification.CategoryAlarm);
                    //notificationBuilder.SetSmallIcon(Resource.Drawable.transparentNotification);
                    notificationBuilder.SetSmallIcon(Resource.Drawable.logo);
                    //notificationBuilder.SetColor(Resources.GetColor(Resource));
                    notificationBuilder.SetVibrate(new long[] { 100, 200, 300 });
                }
                else
                {
                    notificationBuilder.SetSmallIcon(Resource.Drawable.logo);
                }

                var notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);
                notificationManager.Notify(i++, notificationBuilder.Build());
            };
        }
コード例 #15
0
        void SendNotification(string message, string title, string imagem = null, string tipo = null, string summary = null)
        {
            var intent = new Intent(this, typeof(MainActivity));

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

            Notification.Builder notificationBuilder = new Notification.Builder(this)
                                                       .SetSmallIcon(Resource.Drawable.icon)
                                                       .SetContentTitle(title)
                                                       .SetContentText(message)
                                                       .SetAutoCancel(true)
                                                       .SetDefaults(NotificationDefaults.Sound | NotificationDefaults.Vibrate)
                                                       .SetContentIntent(pendingIntent)
                                                       .SetVisibility(NotificationVisibility.Public)
                                                       .SetCategory(Notification.CategoryPromo);

            if (tipo.Equals("1"))
            {
                var notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);
                notificationManager.Notify(0, notificationBuilder.Build());
            }
            else if (tipo.Equals("2"))
            {
                var bigText = new Notification.BigTextStyle();
                bigText.BigText(message);
                bigText.SetSummaryText(summary);
                notificationBuilder.SetStyle(bigText);

                var notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);
                notificationManager.Notify(0, notificationBuilder.Build());
            }
            else if (tipo.Equals("3"))
            {
                var bigImage = new Notification.BigPictureStyle();
                bigImage.BigPicture(GetImageBitmapFromUrl(imagem));
                bigImage.SetSummaryText(summary);
                notificationBuilder.SetStyle(bigImage);

                var notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);
                notificationManager.Notify(0, notificationBuilder.Build());
            }
        }
コード例 #16
0
ファイル: NotificationService.cs プロジェクト: hs5pee/M2Mqtt
        public void createNotification(String title, String body)
        {
            Random rnd   = new Random();
            int    month = rnd.Next(1, 99999);

            Notification.Builder builder = new Notification.Builder(this)
                                           .SetContentTitle(title)
                                           .SetContentText(body)
                                           .SetSmallIcon(Resource.Drawable.monoandroidsplash)
                                           .SetDefaults(NotificationDefaults.Sound);

            Notification.BigTextStyle textStyle = new Notification.BigTextStyle();
            textStyle.BigText(body);
            builder.SetStyle(textStyle);

            Notification        notification        = builder.Build();
            NotificationManager notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;

            notificationManager.Notify(month, notification);
        }
コード例 #17
0
        void SendNotificationRespostaPedido(string message, string trans)
        {
            Log.Debug("Notification", "Chegou aqui notificacao");

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

            //Bundle b = new Bundle();
            //b.PutBoolean("notification",true);
            //b.putInt("num_gcm", id);
            intent.PutExtra("notification", "resposta_pedido");
            //intent.PutExtra("valor", trans_valor);
            //intent.PutExtra("trans_vencimento", trans_vencimento);
            //intent.PutExtra("trans_data", trans_data);
            //intent.PutExtra("nome_user", nome_user);
            //intent.PutExtra("trans_id_user2", trans_id_user2);
            //intent.PutExtra("trans_resposta_pedido", trans_resposta_pedido);
            //intent.PutExtra("trans_dias", trans_dias);

            intent.PutExtra("transacao", trans);

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

            var notificationBuilder = new Notification.Builder(this)
                                      .SetSmallIcon(Resource.Drawable.icon)
                                      .SetContentTitle("InBanker")
                                      .SetContentText(message)
                                      .SetAutoCancel(true)
                                      .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification))
                                      .SetContentIntent(pendingIntent);


            Notification.BigTextStyle bigText = new Notification.BigTextStyle();
            bigText.BigText(message);
            notificationBuilder.SetStyle(bigText);

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

            notificationManager.Notify(0, notificationBuilder.Build());
        }
コード例 #18
0
        public override void OnReceive(Context context, Intent intent)
        {
            var message = intent.GetStringExtra("message");
            var title   = intent.GetStringExtra("title");
            var feature = intent.GetStringExtra("feature");

            var notIntent     = new Intent(context, typeof(MainActivity));
            var contentIntent = PendingIntent.GetActivity(context, 0, notIntent, PendingIntentFlags.UpdateCurrent);


            var manager = (NotificationManager)context.GetSystemService(Context.NotificationService) as NotificationManager;

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

            // Message to Display
            textStyle.BigText(message);

            // Set the summary text as feature label
            textStyle.SetSummaryText(feature);

            // Instantiate the builder and set notification elements:
            Notification.Builder builder = new Notification.Builder(Android.App.Application.Context)
                                           .SetContentIntent(contentIntent)
                                           .SetContentTitle(title)
                                           .SetSmallIcon(Resource.Drawable.ic_info_outline_white_48dp)
                                           .SetDefaults(NotificationDefaults.Sound)
                                           .SetShowWhen(true)
                                           .SetAutoCancel(true)
                                           .SetStyle(textStyle);


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

            // Publish the notification:
            const int notificationId = 0;

            manager.Notify(0, notification);
        }
コード例 #19
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);
        }
コード例 #20
0
		private void generateNotification (string message, string objectId)
		{
			Intent intent = new Intent (this, typeof(MainActivity));
			intent.PutExtra (Const.OBJECT_ID, objectId);

			PendingIntent pendingIntent = PendingIntent.GetActivity (this, notificationId++, intent, PendingIntentFlags.OneShot);

			Notification.Builder builder = new Notification.Builder (this)
				.SetContentIntent (pendingIntent)
				.SetContentTitle (Localization.GetString (Const.APP_NAME))
				.SetContentText (message)
				.SetSmallIcon (Resource.Drawable.icon);

			Notification.BigTextStyle longText = new Notification.BigTextStyle (builder);
			longText.BigText (message);
			longText.SetSummaryText (GetString ("HurryUp"));

			Notification notification = builder.Build ();
			notification.Flags = NotificationFlags.AutoCancel;

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

			notificationManager.Notify (notificationId, notification);
		}
コード例 #21
0
        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            var    prefs         = GetSharedPreferences("KiedyTest", FileCreationMode.Private);
            int    req_timeout   = prefs.GetInt("connection_timeout", 0);
            string heartbeat_url = "http://dziennik.zs1debica.pl/kiedytest/android/request_handler/heartbeat.php?app_type=uczen&app_version=1.0";

            ////// HEARTBEAT EXCUTER ///////
            _timer = new Timer(o => {
                try
                {
                    HttpWebRequest request   = (HttpWebRequest)WebRequest.Create(heartbeat_url);
                    request.Timeout          = req_timeout;
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        Stream receiveStream    = response.GetResponseStream();
                        StreamReader readStream = null;

                        if (response.CharacterSet == null)
                        {
                            readStream = new StreamReader(receiveStream);
                        }
                        else
                        {
                            readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
                        }

                        data = readStream.ReadToEnd();

                        response.Close();
                        readStream.Close();
                    }
                    network_ok = true;
                }
                catch (WebException ex)
                {
                    network_ok = false;
                }
            },
                               null,
                               0,
                               60000); /// Koniec timera
            ///////////////////////////////
            string content, content2;
            string user_name     = prefs.GetString("login", null);
            string user_password = prefs.GetString("password", null);
            string urlAddress    = "http://dziennik.zs1debica.pl/kiedytest/android/request_handler/get_planned_test_notification.php?user_name=" + user_name + "&user_password="******"notify_enabled", null);

                if (notify_enabled == "yes")
                {
                    try
                    {
                        HttpWebRequest request   = (HttpWebRequest)WebRequest.Create(urlAddress);
                        request.Timeout          = req_timeout;
                        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            Stream receiveStream    = response.GetResponseStream();
                            StreamReader readStream = null;

                            if (response.CharacterSet == null)
                            {
                                readStream = new StreamReader(receiveStream);
                            }
                            else
                            {
                                readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
                            }

                            data = readStream.ReadToEnd();

                            response.Close();
                            readStream.Close();
                        }
                        network_ok = true;
                    }
                    catch (WebException ex)
                    {
                        network_ok = false;
                    }
                    content2 = data;
                    //////////////////////////
                    if (network_ok)
                    {
                        content = data;

                        try
                        {
                            content = content.Replace("\x00", "");  //  // AWESOME !!!!! // in my case I want to see it, otherwise just replace with ""
                            MemoryStream memStream = new MemoryStream();
                            byte[] data2           = System.Text.Encoding.UTF8.GetBytes(content);
                            memStream.Write(data2, 0, data2.Length);
                            memStream.Position = 0;
                            XmlDocument doc    = new XmlDocument();
                            doc.LoadXml(content);
                            string noti_type;
                            int noti_type_INT;
                            noti_type_INT = 0;
                            string noti_test_id;
                            noti_test_id = null;
                            int noti_test_id_INT;
                            noti_test_id_INT = 0;
                            string noti_pending;
                            noti_pending = null;
                            int noti_pending_INT;
                            noti_pending_INT = 0;
                            noti_type        = "kot";
                            int c            = 0;

                            string noti_body;
                            noti_body = null;


                            string vibration, sound;
                            vibration = null;
                            sound     = null;
                            int vibration_INT, sound_INT;
                            vibration_INT = 0;
                            sound_INT     = 0;

                            foreach (XmlElement x in doc.SelectNodes("notification/notification_data/notification_type"))
                            {
                                c++;
                                noti_type = x.InnerXml;
                                Console.Write(x.InnerXml);
                            }

                            ////// Checking if any notifications available ////////
                            foreach (XmlElement x in doc.SelectNodes("notification/notification_data/pending_notifications_count"))
                            {
                                c++;
                                noti_pending = x.InnerXml;
                                Console.Write(x.InnerXml);
                            }
                            ////// Checking test id ////////
                            foreach (XmlElement x in doc.SelectNodes("notification/notification_data/test_id"))
                            {
                                c++;
                                noti_test_id = x.InnerXml;
                                Console.Write(x.InnerXml);
                            }
                            ////// Checking notification text ////////
                            foreach (XmlElement x in doc.SelectNodes("notification/notification_data/notification_body"))
                            {
                                c++;
                                noti_body = x.InnerXml;
                                Console.Write(x.InnerXml);
                            }
                            ////// Checking if user enabled sound ////////
                            foreach (XmlElement x in doc.SelectNodes("notification/notification_data/sound"))
                            {
                                c++;
                                sound = x.InnerXml;
                                Console.Write(x.InnerXml);
                            }
                            ////// Checking if user enabled vibration ////////
                            foreach (XmlElement x in doc.SelectNodes("notification/notification_data/vibration"))
                            {
                                c++;
                                vibration = x.InnerXml;
                                Console.Write(x.InnerXml);
                            }

                            /// Converting variables//////////////////
                            int.TryParse(noti_pending, out noti_pending_INT);
                            int.TryParse(noti_type, out noti_type_INT);
                            //int.TryParse(noti_test_id, out noti_test_id_INT);
                            int.TryParse(sound, out sound_INT);
                            int.TryParse(vibration, out vibration_INT);
                            ///////////////////////////////////////
                            if (noti_pending_INT > 0)
                            {
                                /// DATA FOR OTHER ACTIVITY///
                                int test_id;
                                int randomcount;
                                //   float count2;
                                //    count2 = 08.06f;
                                test_id = noti_test_id_INT;
                                Bundle valuesForActivity = new Bundle();
                                valuesForActivity.PutString("test_id", noti_test_id);
                                if (noti_type_INT == 1)
                                {
                                    valuesForActivity.PutString("display_type", "onlyone");
                                }

                                if (noti_type_INT == 2)
                                {
                                    if (noti_pending_INT > 1)
                                    {
                                        valuesForActivity.PutString("display_type", "all");
                                    }
                                    else
                                    {
                                        valuesForActivity.PutString("display_type", "onlyone");
                                    }
                                }

                                // When the user clicks the notification, SecondActivity will start up.
                                Intent resultIntent = new Intent(this, typeof(Activity1));
                                // Pass some values to SecondActivity:
                                resultIntent.PutExtras(valuesForActivity);
                                // Construct a back stack for cross-task navigation:
                                TaskStackBuilder stackBuilder = TaskStackBuilder.Create(this);
                                stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(Activity1)));
                                stackBuilder.AddNextIntent(resultIntent);
                                // Create the PendingIntent with the back stack:
                                PendingIntent resultPendingIntent =
                                    stackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent);
                                /////////////////////////////////////////////////////////////////////////////////
                                if (noti_type_INT == 1)
                                {
                                    // Build the notification:
                                    Notification.Builder builder = new Notification.Builder(this)
                                                                   .SetAutoCancel(true)                         // Dismiss from the notif. area when clicked
                                                                   .SetContentIntent(resultPendingIntent)       // Start 2nd activity when the intent is clicked.
                                                                   .SetContentTitle("Nowy zapowiedziany test!") // Set its title
                                                                                                                //  .SetNumber(count)                          // Display the count in the Content Info
                                                                   .SetSmallIcon(App7.Resource.Drawable.Icon)   // Display this icon
                                                                   .SetContentText(String.Format(
                                                                                       noti_body));             // The message to display.
                                    // Finally, publish the notification:
                                    NotificationManager notificationManager =
                                        (NotificationManager)GetSystemService(Context.NotificationService);
                                    Random rand1 = new Random();
                                    randomcount  = rand1.Next();

                                    if (sound_INT == 1 && vibration_INT == 1)
                                    {
                                        builder.SetDefaults(NotificationDefaults.Sound | NotificationDefaults.Vibrate);
                                    }
                                    else if (sound_INT == 1)
                                    {
                                        builder.SetDefaults(NotificationDefaults.Sound);
                                    }
                                    else if (vibration_INT == 1)
                                    {
                                        builder.SetDefaults(NotificationDefaults.Vibrate);
                                    }

                                    //  builder.SetDefaults( NotificationDefaults.Vibrate);
                                    notificationManager.Notify(randomcount, builder.Build());
                                }
                                if (noti_type_INT == 2)
                                {
                                    string new_test_parsed_title;

                                    if (noti_pending_INT > 1)
                                    {
                                        new_test_parsed_title = "Nowe zapowiedziane testy!";
                                    }
                                    else
                                    {
                                        new_test_parsed_title = "Nowy zapowiedziany test!";
                                    }
                                    // Build the notification:
                                    Notification.Builder builder = new Notification.Builder(this)
                                                                   .SetAutoCancel(true)                       // Dismiss from the notif. area when clicked
                                                                   .SetContentIntent(resultPendingIntent)     // Start 2nd activity when the intent is clicked.
                                                                   .SetContentTitle(new_test_parsed_title)    // Set its title
                                                                                                              //  .SetNumber(count)                          // Display the count in the Content Info
                                                                   .SetSmallIcon(App7.Resource.Drawable.Icon) // Display this icon
                                                                   .SetContentText(String.Format(
                                                                                       noti_body));           // The message to display.
                                    // Instantiate the Big Text style:
                                    Notification.BigTextStyle textStyle = new Notification.BigTextStyle();
                                    // Fill it with text:
                                    string longTextMessage = noti_body;
                                    // longTextMessage += " / Just like me. ";
                                    //...
                                    textStyle.BigText(longTextMessage);
                                    // Set the summary text:
                                    if (noti_pending_INT == 1)
                                    {
                                        tests_grammar = " nowy zapowiedziany test";
                                    }
                                    if (noti_pending_INT > 1 && noti_pending_INT < 5)
                                    {
                                        tests_grammar = " nowe zapowiedziane testy";
                                    }
                                    if (noti_pending_INT > 5)
                                    {
                                        tests_grammar = " nowych zapowiedzianych testów";
                                    }
                                    textStyle.SetSummaryText(noti_pending + tests_grammar);
                                    // Plug this style into the builder:
                                    builder.SetStyle(textStyle);
                                    // Finally, publish the notification:
                                    NotificationManager notificationManager =
                                        (NotificationManager)GetSystemService(Context.NotificationService);
                                    Random rand1 = new Random();
                                    randomcount  = rand1.Next();
                                    if (sound_INT == 1 && vibration_INT == 1)
                                    {
                                        builder.SetDefaults(NotificationDefaults.Sound | NotificationDefaults.Vibrate);
                                    }
                                    else if (sound_INT == 1)
                                    {
                                        builder.SetDefaults(NotificationDefaults.Sound);
                                    }
                                    else if (vibration_INT == 1)
                                    {
                                        builder.SetDefaults(NotificationDefaults.Vibrate);
                                    }
                                    //  builder.SetDefaults( NotificationDefaults.Vibrate);
                                    notificationManager.Notify(randomcount, builder.Build());
                                }
                            }
                        }

                        catch (Exception ex)
                        {
                            // just suppress any error logging exceptions
                        }
                    } /// IF network ok END
                }
            },
                               null,
                               0,
                               TimerWait); /// Koniec timera
            return(START_STICKY);
        }
コード例 #22
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.activity_notifications);
            ActionBar.SetDisplayHomeAsUpEnabled(true);
            ActionBar.SetDisplayShowHomeEnabled(true);
            ActionBar.SetIcon(Android.Resource.Color.Transparent);
            highPriority = FindViewById <Switch> (Resource.Id.high_priority);

            var intent        = new Intent(this, typeof(NotificationsActivity));
            var contentIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.CancelCurrent);

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


            FindViewById <Button>(Resource.Id.simple).Click += (sender, e) => {
                manager.Cancel(0);

                //Generate a notification with just short text and small icon
                var builder = new Notification.Builder(this)
                              .SetContentIntent(contentIntent)
                              .SetSmallIcon(Resource.Drawable.ic_notification)
                              .SetContentTitle("Daniel")
                              .SetContentText("I went to the zoo and saw a monkey!")
                              .SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis())
                              .SetAutoCancel(true);

                SetMetadata(builder);

                var notification = builder.Build();
                if (highPriority.Checked)
                {
                    notification.Defaults |= NotificationDefaults.Sound;
                }
                manager.Notify(0, notification);
            };


            FindViewById <Button>(Resource.Id.simple_photo).Click += (sender, e) => {
                manager.Cancel(1);

                var icon = BitmapFactory.DecodeResource(Resources, Resource.Drawable.over_there);
                //Generate a notification with just short text, small icon & large icon
                var builder = new Notification.Builder(this)
                              .SetContentIntent(contentIntent)
                              .SetSmallIcon(Resource.Drawable.ic_notification)
                              .SetLargeIcon(icon)
                              .SetContentTitle("Daniel")
                              .SetContentText("I went to the zoo and saw a monkey!")
                              .SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis())
                              .SetAutoCancel(true);

                SetMetadata(builder);

                var notification = builder.Build();
                if (highPriority.Checked)
                {
                    notification.Defaults |= NotificationDefaults.Sound;
                }
                manager.Notify(1, notification);

                icon.Recycle();
            };

            FindViewById <Button>(Resource.Id.extended).Click += (sender, e) => {
                manager.Cancel(2);

                var icon = BitmapFactory.DecodeResource(Resources, Resource.Drawable.over_there);

                //Extended with big text
                var message = "I went to the zoo and saw a monkey! And then I saw even more awesome stuff and itt was great and then we went back to see the monkeys again.";
                var style   = new Notification.BigTextStyle();
                style.BigText(message);
                style.SetSummaryText(message);
                var builder = new Notification.Builder(this)
                              .SetContentIntent(contentIntent)
                              .SetSmallIcon(Resource.Drawable.ic_notification)
                              .SetLargeIcon(icon)
                              .SetStyle(style)
                              .SetContentTitle("Daniel")
                              .SetContentText(message)
                              .SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis())
                              .SetAutoCancel(true);

                SetMetadata(builder);

                var notification = builder.Build();
                if (highPriority.Checked)
                {
                    notification.Defaults |= NotificationDefaults.Sound;
                }
                manager.Notify(2, notification);
                icon.Recycle();
            };

            FindViewById <Button>(Resource.Id.extended_photo).Click += (sender, e) => {
                manager.Cancel(3);

                //Extended with big text
                var message = "I went to the zoo and saw a monkey! And then I saw even more awesome stuff and itt was great and then we went back to see the monkeys again.";
                var style   = new Notification.BigPictureStyle();
                var icon    = BitmapFactory.DecodeResource(Resources, Resource.Drawable.over_there);

                style.BigPicture(icon);
                style.SetSummaryText(message);
                var builder = new Notification.Builder(this)
                              .SetContentIntent(contentIntent)
                              .SetSmallIcon(Resource.Drawable.ic_notification)
                              .SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.evolve))
                              .SetStyle(style)
                              .SetContentTitle("Daniel")
                              .SetContentText(message)
                              .SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis())
                              .SetAutoCancel(true);

                SetMetadata(builder);

                var notification = builder.Build();
                if (highPriority.Checked)
                {
                    notification.Defaults |= NotificationDefaults.Sound;
                }
                manager.Notify(3, notification);

                icon.Recycle();
            };

            spinner = FindViewById <Spinner>(Resource.Id.spinner_visibility);
            // Create an ArrayAdapter using the string array and a default spinner layout
            var adapter = ArrayAdapter.CreateFromResource(this,
                                                          Resource.Array.notification_priority, Android.Resource.Layout.SimpleSpinnerItem);

            // Specify the layout to use when the list of choices appears
            adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
            // Apply the adapter to the spinner
            spinner.Adapter = adapter;
        }
コード例 #23
0
        async Task SendNotificationAsync(RemoteMessage message)
        {
            string notificationType = message.Data["type"];
            string idAlarm          = message.Data["idAlarm"];
            string idRoom           = message.Data["idRoom"];
            string numRoom          = message.Data["numRoom"];
            string nomOccupant      = message.Data["occupant"];
            string triggerTime      = message.Data["triggerTime"];
            //Personnalisation du message de la notification
            string notifTitle   = "Nouvel appel en chambre " + numRoom + " !";
            string notifMessage = "Appel effectué à " + triggerTime;

            //S'il s'agit d'une notification de type nouvelle alarme
            if (notificationType.Equals("newAlarm"))
            {
                //Ajout de l'alarme dans la base de données locale
                AlarmItem alarm = new AlarmItem();
                alarm.IDAlarm     = int.Parse(idAlarm);
                alarm.Status      = false;
                alarm.Chambre     = numRoom;
                alarm.NomOccupant = nomOccupant;
                alarm.DtDebut     = triggerTime;

                AlarmItemManager.AddAlarm(alarm);

                Console.WriteLine(AlarmItemManager.GetAlarm(4).Chambre);
            }



            //Affichage de la notification que nous venons de configurer
            var intent = new Intent(this, typeof(Accueil));

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

            Notification.BigTextStyle textStyle = new Notification.BigTextStyle();

            //...
            textStyle.BigText(notifMessage);


            var notificationBuilder = new Notification.Builder(this)
                                      .SetContentTitle(notifTitle)
                                      .SetStyle(textStyle)
                                      .SetContentText(notifMessage)
                                      .SetPriority((int)Android.App.NotificationPriority.High)
                                      .SetDefaults(NotificationDefaults.Vibrate)
                                      .SetSmallIcon(Resource.Drawable.patient2)
                                      .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Alarm))
                                      .SetAutoCancel(true)
                                      .SetContentIntent(pendingIntent)
                                      .SetVisibility(NotificationVisibility.Public);



            if (notificationType.Equals("newAlarm") || (notificationType.Equals("support") && notifyNewSupport))
            {
                var notificationManager = NotificationManager.FromContext(this);
                notificationManager.Notify(int.Parse(idRoom), notificationBuilder.Build());
            }
        }
コード例 #24
0
        public override void OnCreate()
        {
            instancia = this;
            IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
            foreach (IPAddress ip in localIPs)
            {
                if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    ipadre = ip.ToString();
                }
            }



            new Thread(() =>
            {
                if (CheckInternetConnection())
                {
                    bool notienenada = false;

                    WebClient cliente = new WebClient();
                    cliente.DownloadDataAsync(new Uri("https://raw.githubusercontent.com/Gr3gorywolf/Multitube.android/master/Updates/version.gr3v"));
                    cliente.DownloadDataCompleted += (aaa, aaaa) =>
                    {
                        string versionsinparsear = Encoding.UTF8.GetString(aaaa.Result);
                        if (!File.Exists(Android.OS.Environment.ExternalStorageDirectory.ToString() + "/.gr3cache/version.gr3v"))
                        {
                            notienenada = true;
                        }
                        if (notienenada)
                        {
                            MultitubeWebHelper.UpdateMultitubeWeb(versionsinparsear);
                        }
                        else
                        {
                            if (versionsinparsear != File.ReadAllText(Android.OS.Environment.ExternalStorageDirectory.ToString() + "/.gr3cache/version.gr3v"))
                            {
                                MultitubeWebHelper.UpdateMultitubeWeb(versionsinparsear);
                            }
                        }
                    };
                    if (Constants.UseFirebase)
                    {
                        meterdata();
                    }
                }
                else
                {
                }
            }).Start();
            if (servidor != null)
            {
                servidor.Stop();
            }

            servidor = new MultitubeWebServer(Android.OS.Environment.ExternalStorageDirectory.ToString(), 12345, ipadre, this);
            var pelo = new Thread(() =>
            {
                checkchange();
            });

            pelo.IsBackground = true;
            pelo.Start();



            var brandom = new Random();

            Intent internado2     = new Intent(this, typeof(serviciointerpreter23));
            Intent internado3     = new Intent(this, typeof(serviciointerpreter234));
            var    pendingIntent3 = PendingIntent.GetService(ApplicationContext, brandom.Next(2000, 50000) + brandom.Next(2000, 50000), internado3, 0);
            var    pendingIntent2 = PendingIntent.GetService(ApplicationContext, brandom.Next(2000, 50000) + brandom.Next(2000, 50000), internado2, 0);

            Notification.Action accion  = new Notification.Action(Resource.Drawable.drwaable, "Parar", pendingIntent2);
            Notification.Action accion2 = new Notification.Action(Resource.Drawable.drwaable, "Conectarse", pendingIntent3);

            Notification.BigTextStyle textoo = new Notification.BigTextStyle();
            textoo.SetBigContentTitle("Stremeando en " + ipadre + ":12345");
            textoo.SetSummaryText("Toque para parar de stremear su media");
            textoo.BigText("Para conectarse introduzca " + ipadre + ":12345  " + "en su navegador o entre a multitubeweb.tk y toque conectar luego escanee el codigo que aparece al presionar el boton de + en multitubeweb.   al tocar parar se cierrar el servicio de streaming");


#pragma warning disable CS0618 // El tipo o el miembro están obsoletos
            Notification.Builder nBuilder = new Notification.Builder(this);
#pragma warning restore CS0618 // El tipo o el miembro están obsoletos
            nBuilder.SetContentTitle("Stremeando en " + ipadre + ":12345");
            nBuilder.SetContentText("Toque para parar de stremear su media");

            nBuilder.SetOngoing(true);
            //  nBuilder.SetContentIntent(pendingIntent2);
            nBuilder.SetStyle(textoo);
            nBuilder.SetSmallIcon(Resource.Drawable.antena);
            nBuilder.SetColor(Android.Graphics.Color.ParseColor("#ce2c2b"));
            nBuilder.AddAction(accion);
            nBuilder.AddAction(accion2);

            Notification notification = nBuilder.Build();
            StartForeground(193423456, notification);
            base.OnCreate();
            //  descargar(intent.GetStringExtra("path"), intent.GetStringExtra("archivo"), intent.GetStringExtra("titulo"), intent.GetStringExtra("link"));
        }
コード例 #25
0
        public async override void OnReceive(Context context, Intent intent)
        {
            try
            {
                var setupSingleton = MvxAndroidSetupSingleton.EnsureSingletonAvailable(context);
                setupSingleton.EnsureInitialized();

                RealmService   = new CryptoRealmService();
                CryptoDelegate = new CryptoDelegate();

                var cryptoCurrencies = await CryptoDelegate.GetCryptoCurrencyList();

                if (cryptoCurrencies != null && cryptoCurrencies.Count > 0)
                {
                    var searchDto = new ReminderSearchDto
                    {
                        Type = SearchType.AllReminders
                    };

                    var    reminders = RealmService.GetReminder(searchDto);
                    string message   = "";

                    foreach (var reminder in reminders)
                    {
                        var cryptoCurrency = cryptoCurrencies.FirstOrDefault(x => x.MarketName == reminder.MarketName);

                        if (cryptoCurrency == null)
                        {
                            continue;
                        }

                        if (reminder.IsExactValueSet && cryptoCurrency.Last == reminder.ExactValue)
                        {
                            message += reminder.MarketName + " has reached " + reminder.ExactValue.ConvertExpo() + ". \n";
                        }

                        if (reminder.IsLowerLimitSet && cryptoCurrency.Last < reminder.LowerLimit)
                        {
                            message += reminder.MarketName + " has gone below " + reminder.LowerLimit.ConvertExpo() + ". It's current value is " + cryptoCurrency.Last.ConvertExpo() + ". \n";
                        }

                        if (reminder.IsUpperLimitSet && cryptoCurrency.Last > reminder.UpperLimit)
                        {
                            message += reminder.MarketName + " has gone above " + reminder.UpperLimit.ConvertExpo() + ". It's current value is " + cryptoCurrency.Last.ConvertExpo() + ". \n";
                        }
                    }

                    message.TrimEnd('\r', '\n');

                    if (string.IsNullOrEmpty(message))
                    {
                        return;
                    }

                    Notification.BigTextStyle textStyle = new Notification.BigTextStyle();
                    textStyle.BigText(message);
                    Notification.Builder builder = new Notification.Builder(context)
                                                   .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification))
                                                   .SetContentTitle("Crypto Reminder.")
                                                   .SetSmallIcon(Resource.Drawable.notification_bg)
                                                   .SetStyle(textStyle);

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

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

                    // Publish the notification:
                    const int notificationId = 0;
                    notificationManager.Notify(notificationId, notification);
                }
            }
            catch (Exception ex)
            {
            }
        }
コード例 #26
0
        private void startMyService()
        {
            //create the default activity to be shown
            Intent        intent  = new Intent();
            PendingIntent pending = PendingIntent.GetActivity(this, 0, intent, 0);


            if (Android.OS.Build.VERSION.SdkInt <= BuildVersionCodes.NMr1)
            {
                var notification = new Notification.Builder(this, Constants.CHANNEL_ID)
                                   .SetContentTitle(Constants.CONTENT_TITLE)
                                   .SetContentText(Constants.CONTENT_TEXT)
                                   .SetSmallIcon(Resource.Drawable.bsplash)
                                   .SetOngoing(true)
                                   .Build();

                StartForeground(300, notification);
            }

            else
            {
                //create a notification channel. this is a must if your service is going to run on
                //Android 8.0(Oreo) and above
                NotificationChannel channel = new NotificationChannel(MPConstants.CHANNEL_ID1, MPConstants.CHANNEL_NAME, NotificationImportance.Default);
                NotificationManager manager = GetSystemService(NotificationService) as NotificationManager;

                if (manager != null)
                {
                    manager.CreateNotificationChannel(channel);
                }

                //create the notification
                var builder = new Notification.Builder(this, MPConstants.CHANNEL_ID1);

                //make notification show big text
                Notification.BigTextStyle BigStyle = new Notification.BigTextStyle();
                BigStyle.SetBigContentTitle("This service is running in the foreground");
                BigStyle.BigText("This is a music like foreground service that was built using some tutorial and some little tweaks");
                builder.SetStyle(BigStyle);

                //build notification
                builder.SetWhen(DateTime.Now.Millisecond);
                builder.SetSmallIcon(Resource.Drawable.badge);
                //////set large icon of type Bitmap
                //Bitmap LargeIconBitMap = BitmapFactory.DecodeResource(Resources.get, Resource.Drawable.bsplash);

                //used to set full screen intent
                builder.SetFullScreenIntent(pending, true);

                //Add play button to Notification
                Intent PlayIntent = new Intent(this, typeof(MusicService));
                intent.SetAction(MPConstants.ACTION_PLAY);
                PendingIntent       PendingPlayIntent = PendingIntent.GetService(this, 0, PlayIntent, 0);
                Notification.Action playaction        = new Notification.Action(Resource.Drawable.ic_media_play_light, "Play", PendingPlayIntent);
                builder.AddAction(playaction);

                //add Pause button to Notification
                Intent PauseIntent = new Intent(this, typeof(MusicService));
                intent.SetAction(MPConstants.ACTION_PAUSE);
                PendingIntent       PausePendingIntent = PendingIntent.GetService(this, 0, PauseIntent, 0);
                Notification.Action PauseAction        = new Notification.Action(Resource.Drawable.ic_media_pause_light, "Pause", PausePendingIntent);
                builder.AddAction(PauseAction);

                //build notification
                Notification notification = builder.Build();

                StartForeground(500, notification);
            }
        }
コード例 #27
0
ファイル: MainActivity.cs プロジェクト: ycwu/XFWorkShop
        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
        }
コード例 #28
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);

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

            //------------------------------------------------------------------
            // Display Cutout Mode demo

            Button shortEdgesBtn = FindViewById <Button>(Resource.Id.short_btn);
            Button neverBtn      = FindViewById <Button>(Resource.Id.never_btn);
            Button resetBtn      = FindViewById <Button>(Resource.Id.reset_btn);

            shortEdgesBtn.Click += (sender, e) =>
            {
                Window.Attributes.LayoutInDisplayCutoutMode =
                    Android.Views.LayoutInDisplayCutoutMode.ShortEdges;
                Window.AddFlags(WindowManagerFlags.Fullscreen);
                Toast.MakeText(this, "Cutout Short Edges", ToastLength.Short).Show();
            };

            neverBtn.Click += (sender, e) =>
            {
                Window.Attributes.LayoutInDisplayCutoutMode =
                    Android.Views.LayoutInDisplayCutoutMode.Never;
                Window.AddFlags(WindowManagerFlags.Fullscreen);
                Toast.MakeText(this, "Cutout Never", ToastLength.Short).Show();
            };

            resetBtn.Click += (sender, e) =>
            {
                Window.Attributes.LayoutInDisplayCutoutMode =
                    Android.Views.LayoutInDisplayCutoutMode.Never;
                Window.ClearFlags(WindowManagerFlags.Fullscreen);
                Toast.MakeText(this, "Reset to non Full-screen", ToastLength.Short).Show();
            };

            //------------------------------------------------------------------
            // Image Notification demo:

            Button notifBtn = FindViewById <Button>(Resource.Id.notification_btn);

            notifBtn.Click += (sender, e) =>
            {
                // Create a demo notification channel for notifications in this app:
                string chanName          = GetString(Resource.String.noti_chan_demo);
                var    importance        = NotificationImportance.High;
                NotificationChannel chan = new NotificationChannel(DEMO_CHANNEL, chanName, importance);
                chan.EnableVibration(true);
                chan.LockscreenVisibility = NotificationVisibility.Public;
                NotificationManager notificationManager =
                    (NotificationManager)GetSystemService(NotificationService);
                notificationManager.CreateNotificationChannel(chan);

                // Create a Person object that represents the sender:
                Icon   senderIcon = Icon.CreateWithResource(this, Resource.Drawable.sender_icon);
                Person fromPerson = new Person.Builder()
                                    .SetIcon(senderIcon)
                                    .SetName("Mark Sender")
                                    .Build();

                // Create a text notification to send before the image notification:
                Notification.BigTextStyle textStyle = new Notification.BigTextStyle();
                string longTextMessage = "We've just arrived at the Colosseum, let me send";
                longTextMessage += " you a pic before we go inside.";
                textStyle.BigText(longTextMessage);

                // Notification builder using this style:
                Notification.Builder builder = new Notification.Builder(this, DEMO_CHANNEL)
                                               .SetContentTitle("At the Colosseum")
                                               .SetSmallIcon(Resource.Mipmap.ic_notification)
                                               .SetStyle(textStyle)
                                               .SetChannelId(DEMO_CHANNEL);

                // Publish the text notification:
                const int notificationId = 1000;
                notificationManager.Notify(notificationId, builder.Build());

                Thread.Sleep(5000);

                // Send Image notification ...........................................

                // Create a message from the sender with the image to send:
                Uri imageUri = Uri.Parse("android.resource://com.xamarin.pminidemo/drawable/example_image");
                Notification.MessagingStyle.Message message = new Notification.MessagingStyle
                                                              .Message("Here's a picture of where I'm currently standing", 0, fromPerson)
                                                              .SetData("image/", imageUri);

                // Add the message to a notification style:
                Notification.MessagingStyle style = new Notification.MessagingStyle(fromPerson)
                                                    .AddMessage(message);

                // Notification builder using this style:
                builder = new Notification.Builder(this, DEMO_CHANNEL)
                          .SetContentTitle("Tour of the Colosseum")
                          .SetContentText("We're standing in front of the Colosseum and I just took this shot!")
                          .SetSmallIcon(Resource.Mipmap.ic_notification)
                          .SetStyle(style)
                          .SetChannelId(DEMO_CHANNEL);

                // Publish the notification:
                const int notificationId2 = 1001;
                notificationManager.Notify(notificationId2, builder.Build());
            };
        }
コード例 #29
0
		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);
			SetContentView (Resource.Layout.activity_notifications);
			ActionBar.SetDisplayHomeAsUpEnabled (true);
			ActionBar.SetDisplayShowHomeEnabled (true);
			ActionBar.SetIcon (Android.Resource.Color.Transparent);
			highPriority = FindViewById<Switch> (Resource.Id.high_priority);

			var intent = new Intent (this, typeof(NotificationsActivity));
			var contentIntent = PendingIntent.GetActivity (this, 0, intent, PendingIntentFlags.CancelCurrent);

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


			FindViewById<Button>(Resource.Id.simple).Click += (sender, e) => {

				manager.Cancel(0);

				//Generate a notification with just short text and small icon
				var builder = new Notification.Builder(this)
					.SetContentIntent(contentIntent)
					.SetSmallIcon(Resource.Drawable.ic_notification)
					.SetContentTitle("Daniel")
					.SetContentText("I went to the zoo and saw a monkey!")
					.SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis())
					.SetAutoCancel(true);

				SetMetadata(builder);

				var notification = builder.Build();
				if(highPriority.Checked)
					notification.Defaults |= NotificationDefaults.Sound;
				manager.Notify(0, notification);
			};
				

			FindViewById<Button>(Resource.Id.simple_photo).Click += (sender, e) => {

				manager.Cancel(1);

				var icon = BitmapFactory.DecodeResource(Resources, Resource.Drawable.over_there);
				//Generate a notification with just short text, small icon & large icon
				var builder = new Notification.Builder(this)
					.SetContentIntent(contentIntent)
					.SetSmallIcon(Resource.Drawable.ic_notification)
					.SetLargeIcon(icon)
					.SetContentTitle("Daniel")
					.SetContentText("I went to the zoo and saw a monkey!")
					.SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis())
					.SetAutoCancel(true);

				SetMetadata(builder);

				var notification = builder.Build();
				if(highPriority.Checked)
					notification.Defaults |= NotificationDefaults.Sound;
				manager.Notify(1, notification);

				icon.Recycle();
			};

			FindViewById<Button>(Resource.Id.extended).Click += (sender, e) => {

				manager.Cancel(2);

				var icon = BitmapFactory.DecodeResource(Resources, Resource.Drawable.over_there);

				//Extended with big text
				var message = "I went to the zoo and saw a monkey! And then I saw even more awesome stuff and itt was great and then we went back to see the monkeys again.";
				var style = new Notification.BigTextStyle();
				style.BigText(message);
				style.SetSummaryText(message);
				var builder = new Notification.Builder(this)
					.SetContentIntent(contentIntent)
					.SetSmallIcon(Resource.Drawable.ic_notification)
					.SetLargeIcon(icon)
					.SetStyle(style)
					.SetContentTitle("Daniel")
					.SetContentText(message)
					.SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis())
					.SetAutoCancel(true);

				SetMetadata(builder);

				var notification = builder.Build();
				if(highPriority.Checked)
					notification.Defaults |= NotificationDefaults.Sound;
				manager.Notify(2, notification);
				icon.Recycle();
			};

			FindViewById<Button>(Resource.Id.extended_photo).Click += (sender, e) => {

				manager.Cancel(3);

				//Extended with big text
				var message = "I went to the zoo and saw a monkey! And then I saw even more awesome stuff and itt was great and then we went back to see the monkeys again.";
				var style = new Notification.BigPictureStyle();
				var icon = BitmapFactory.DecodeResource(Resources, Resource.Drawable.over_there);

				style.BigPicture(icon);
				style.SetSummaryText(message);
				var builder = new Notification.Builder(this)
					.SetContentIntent(contentIntent)
					.SetSmallIcon(Resource.Drawable.ic_notification)
					.SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.evolve))
					.SetStyle(style)
					.SetContentTitle("Daniel")
					.SetContentText(message)
					.SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis())
					.SetAutoCancel(true);

				SetMetadata(builder);

				var notification = builder.Build();
				if(highPriority.Checked)
					notification.Defaults |= NotificationDefaults.Sound;
				manager.Notify(3, notification);

				icon.Recycle();
			};

			spinner = FindViewById<Spinner>(Resource.Id.spinner_visibility);
			// Create an ArrayAdapter using the string array and a default spinner layout
			var adapter = ArrayAdapter.CreateFromResource(this,
				Resource.Array.notification_priority, Android.Resource.Layout.SimpleSpinnerItem);
			// Specify the layout to use when the list of choices appears
			adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
			// Apply the adapter to the spinner
			spinner.Adapter = adapter;
		}
コード例 #30
0
ファイル: MainActivity.cs プロジェクト: MIliev11/Samples
        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);
            };
        }
コード例 #31
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 { }
        }