Beispiel #1
0
        /// <summary>
        /// Update the notification.
        /// </summary>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <returns>
        /// The updated notification.
        /// </returns>
        public Notification UpdateNotification(Context context)
        {
            var builder = new Notification.Builder(context);

            if (!string.IsNullOrEmpty(this.PausedText))
            {
                builder.SetContentTitle(this.PausedText);
                builder.SetContentText(string.Empty);
                builder.SetContentInfo(string.Empty);
            }
            else
            {
                builder.SetContentTitle(this.Title);
                if (this.TotalBytes > 0 && this.CurrentBytes != -1)
                {
                    builder.SetProgress((int)(this.TotalBytes >> 8), (int)(this.CurrentBytes >> 8), false);
                }
                else
                {
                    builder.SetProgress(0, 0, true);
                }

                builder.SetContentText(Helpers.GetDownloadProgressString(this.CurrentBytes, this.TotalBytes));
                builder.SetContentInfo(string.Format("{0}s left", Helpers.GetTimeRemaining(this.TimeRemaining)));
            }

            builder.SetSmallIcon(this.Icon != 0 ? this.Icon : Android.Resource.Drawable.StatSysDownload);
            builder.SetOngoing(true);
            builder.SetTicker(this.Ticker);
            builder.SetContentIntent(this.PendingIntent);

            return(builder.Notification);
        }
Beispiel #2
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);
            }
        }
Beispiel #3
0
        private void HandleEnterZone(Zone z)
        {
            Log.Debug(TAG, "Enter zone " + z.Name);

            Intent notificationIntent = new Intent(this, typeof(NotificationActivity));

            notificationIntent.PutExtra("zone_id", z.Id);
            notificationIntent.PutExtra("zone_name", z.Name);
            notificationIntent.PutExtra("zone_color", z.Color);
            notificationIntent.PutExtra("zone_alias", z.Alias);

            PendingIntent pendingIntent = PendingIntent.GetActivity(
                this,
                z.Id,
                notificationIntent,
                PendingIntentFlags.UpdateCurrent);

            Notification.Builder notificationBuilder = new Notification.Builder(this);
            notificationBuilder.SetSmallIcon(Resource.Drawable.elm_logo);
            notificationBuilder.SetContentTitle("New zone");
            notificationBuilder.SetContentText("You have entered zone '" + z.Name + "'");
            notificationBuilder.SetDefaults(NotificationDefaults.Sound);
            notificationBuilder.SetAutoCancel(true);
            notificationBuilder.SetContentIntent(pendingIntent);

            // Get an instance of the NotificationManager service
            NotificationManager notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);

            //Build the notification and issues it with notification manager.
            notificationManager.Notify(z.Id, notificationBuilder.Build());
        }
        //internal static bool
        void HandleNotification(string messageBody, string messageTitle)
        {
            var intent = new Intent(Forms.Context, typeof(MainActivity));

            intent.AddFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop);
            var pendingIntent = PendingIntent.GetActivity(Forms.Context, 0, intent, PendingIntentFlags.UpdateCurrent);


            var n = new Notification.Builder(Forms.Context);

            n.SetSmallIcon(Resource.Drawable.notification_template_icon_bg);
            n.SetLights(Android.Graphics.Color.Blue, 300, 1000);
            n.SetContentIntent(pendingIntent);
            n.SetContentTitle(messageTitle);
            n.SetTicker(messageBody);
            //n.SetLargeIcon(global::Android.Graphics.BitmapFactory.DecodeResource(context.Resources, Resource.Drawable.icon));
            n.SetAutoCancel(true);
            n.SetContentText(messageBody);
            n.SetVibrate(new long[] {
                200,
                200,
                100,
            });

            var nm = NotificationManager.FromContext(Forms.Context);

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

            // Make call to Xamarin.Forms here with the event handler
        }
        private void InitBlockChain()
        {
            if (BlockChainService.BlockChain == null)
            {
                BlockChainService.BlockChain = new BlockChainVotings();

                BlockChainService.BlockChain.CheckRoot();

                Task.Run(() =>
                {
                    BlockChainService.BlockChain.Start();
                });

                BlockChainService.BlockChain.NewVoting += (s, a) =>
                {
                    RunOnUiThread(() =>
                    {
                        var notificationManager     = GetSystemService(NotificationService) as NotificationManager;
                        PendingIntent contentIntent = PendingIntent.GetActivity(this, 0, new Intent(this, typeof(MainActivity)), 0);

                        var builder = new Notification.Builder(this);
                        builder.SetAutoCancel(true);
                        builder.SetContentTitle(Resources.GetString(Resource.String.newVoting));
                        builder.SetContentText(BlockChainService.BlockChain.GetVotingName(a.Data));
                        builder.SetSmallIcon(Resource.Drawable.Icon);
                        builder.SetContentIntent(contentIntent);
                        var notification = builder.Build();

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

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

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

            var builder = new Notification.Builder(this);

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

            ((NotificationManager)this.GetSystemService(NotificationService))
            .Notify(id, builder.Build());
        }
        // Creates a new notification depending on makeHeadsUpNotification.
        public Notification CreateNotification(Context context, Intent intent)
        {
            // indicate that this sms comes from server
            intent.PutExtra("source", "server");

            // Parse bundle extras
            string contactId = intent.GetStringExtra("normalizedPhone");
            string message   = intent.GetStringExtra("message");

            // Getting contact infos
            var contact = Contact.GetContactByPhone(contactId, context);

            var builder = new Notification.Builder(context)
                          .SetSmallIcon(Resource.Drawable.icon)
                          .SetPriority((int)NotificationPriority.Default)
                          .SetCategory(Notification.CategoryMessage)
                          .SetContentTitle(contact.DisplayName != "" ? contact.DisplayName : contactId)
                          .SetContentText(message)
                          .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification));

            var fullScreenPendingIntent = PendingIntent.GetActivity(context, 0,
                                                                    intent, PendingIntentFlags.CancelCurrent);

            builder.SetContentText(message)
            .SetFullScreenIntent(fullScreenPendingIntent, true)
            .SetContentIntent(fullScreenPendingIntent);

            return(builder.Build());
        }
        protected override void OnMessage(Context context, Intent intent)
        {
            string message = string.Empty;

            // Extract the push notification message from the intent.
            if (intent.Extras.ContainsKey("message"))
            {
                message = intent.Extras.Get("message").ToString();
                var title = "Doctor Notification";

                // Create a notification manager to send the notification.
                var notificationManager =
                    GetSystemService(NotificationService) as NotificationManager;

                // Create a new intent to show the notification in the UI.
                PendingIntent contentIntent =
                    PendingIntent.GetActivity(context, 0,
                                              new Intent(this, typeof(MainActivity)), 0);

                // Create the notification using the builder.
                var builder = new Notification.Builder(context);
                builder.SetAutoCancel(true);
                builder.SetContentTitle(title);
                builder.SetContentText(message);
                builder.SetSmallIcon(Resource.Drawable.ic_launcher);
                builder.SetContentIntent(contentIntent);
                var notification = builder.Build();

                // Display the notification in the Notifications Area.
                notificationManager.Notify(1, notification);

                ShowPopUp(context, message);
            }
        }
Beispiel #9
0
        /// <summary>
        /// Update the notification.
        /// </summary>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <returns>
        /// The updated notification.
        /// </returns>
        public Notification UpdateNotification(Context context)
        {
            if (builder == null)
            {
                builder = new Notification.Builder(context);
            }

            builder.SetContentTitle(this.Title);
            if (this.TotalBytes > 0 && this.CurrentBytes != -1)
            {
                builder.SetProgress((int)(this.TotalBytes >> 8), (int)(this.CurrentBytes >> 8), false);
            }
            else
            {
                builder.SetProgress(0, 0, true);
            }
            builder.SetContentText(Helpers.GetDownloadProgressString(this.CurrentBytes, this.TotalBytes));
            builder.SetContentInfo(context.GetString(Resource.String.time_remaining_notification, Helpers.GetTimeRemaining(this.TimeRemaining)));
            builder.SetSmallIcon(this.Icon != 0 ? this.Icon : Android.Resource.Drawable.StatSysDownload);
            builder.SetOngoing(true);
            builder.SetTicker(this.Ticker);
            builder.SetContentIntent(this.PendingIntent);

            return(builder.Notification);
        }
        protected override void OnMessage(Context context, Intent intent)
        {

            string message = string.Empty;

            // Extract the push notification message from the intent.
            if (intent.Extras.ContainsKey("message"))
            {
                message = intent.Extras.Get("message").ToString();
                var title = "Doctor Notification";

                // Create a notification manager to send the notification.
                var notificationManager =
                    GetSystemService(NotificationService) as NotificationManager;

                // Create a new intent to show the notification in the UI. 
                PendingIntent contentIntent =
                    PendingIntent.GetActivity(context, 0,
                    new Intent(this, typeof(MainActivity)), 0);

                // Create the notification using the builder.
                var builder = new Notification.Builder(context);
                builder.SetAutoCancel(true);
                builder.SetContentTitle(title);
                builder.SetContentText(message);
                builder.SetSmallIcon(Resource.Drawable.ic_launcher);
                builder.SetContentIntent(contentIntent);
                var notification = builder.Build();

                // Display the notification in the Notifications Area.
                notificationManager.Notify(1, notification);

                ShowPopUp(context, message);
            }
        }
        void CreateNotification()
        {
            NotificationManager manager = Android.App.Application.Context.GetSystemService(Context.NotificationService) as NotificationManager;
            var builder = new Notification.Builder(Android.App.Application.Context);

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

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

                manager.CreateNotificationChannel(channel);

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

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

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

            builder.SetContentIntent(resultPendingIntent);

            manager.Notify(0, builder.Build());
        }
        private void ExibirInboxNotificacao()
        {
            Notification.Builder builder = new Notification.Builder(this)
                .SetContentTitle ("Sample Notification")
                .SetContentText ("Hello World! This is my first action notification!")
                .SetDefaults (NotificationDefaults.Sound)
                .SetSmallIcon (Resource.Drawable.Icon);

            // Instantiate the Inbox style:
            Notification.InboxStyle inboxStyle = new Notification.InboxStyle();

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

            // Generate a message summary for the body of the notification:
            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);

            Notification notification = builder.Build();

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

            const int notificationId = 0;
            notificationManager.Notify (notificationId, notification);
        }
        public void ShowNotification(string title, string content)
        {
            CreatNotificationChannel();
            Context context     = Android.App.Application.Context;
            var     intent      = getLaucherActivity();
            var     stackBuiler = TaskStackBuilder.Create(context);

            stackBuiler.AddNextIntent(intent);
            var pendingIntent = stackBuiler.GetPendingIntent(0, (int)PendingIntentFlags.UpdateCurrent);

            if (builder == null)
            {
                builder = new Notification.Builder(context, "channel_ID");
            }

            builder.SetAutoCancel(true);
            builder.SetContentTitle(title);
            builder.SetContentIntent(pendingIntent);
            builder.SetContentText(content);
            //

            builder.SetSmallIcon(Resource.Drawable.ic_vol_type_tv_dark);
            // Resource.Drawable.ic_stat_button_click;

            Notification notification = builder.Build();

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

            notificationManager.Notify(NOTIFICATION_ID, notification);
        }
        protected override void OnMessage(Context context, Intent intent)
        {
            var currentActivity = Mvx.Resolve <IMvxAndroidCurrentTopActivity>().Activity;
            var message         = string.Empty;

            // Extract the push notification message from the intent.
            if (intent.Extras.ContainsKey("message"))
            {
                message = intent.Extras.Get("message").ToString();
                var title = "New item added:";

                // Create a notification manager to send the notification.
                var notificationManager =
                    GetSystemService(NotificationService) as NotificationManager;

                // Create a new intent to show the notification in the UI.
                var contentIntent =
                    PendingIntent.GetActivity(context, 0,
                                              new Intent(this, currentActivity.GetType()), 0);

                // Create the notification using the builder.
                var builder = new Notification.Builder(context);
                builder.SetAutoCancel(true);
                builder.SetContentTitle(title);
                builder.SetContentText(message);
                builder.SetSmallIcon(Resource.Drawable.ic_launcher);
                builder.SetContentIntent(contentIntent);
                var notification = builder.Build();

                // Display the notification in the Notifications Area.
                notificationManager.Notify(1, notification);
            }
        }
        // Creates a new notification depending on makeHeadsUpNotification.
        public Notification CreateNotification(Context context, Intent intent)
        {
            // indicate that this sms comes from server
            intent.PutExtra ("source", "server");

            // Parse bundle extras
            string contactId = intent.GetStringExtra("normalizedPhone");
            string message = intent.GetStringExtra("message");

            // Getting contact infos
            var contact = Contact.GetContactByPhone (contactId, context);

            var builder = new Notification.Builder (context)
                .SetSmallIcon (Resource.Drawable.icon)
                .SetPriority ((int)NotificationPriority.Default)
                .SetCategory (Notification.CategoryMessage)
                .SetContentTitle (contact.DisplayName != "" ? contact.DisplayName : contactId)
                .SetContentText (message)
                .SetSound (RingtoneManager.GetDefaultUri (RingtoneType.Notification));

            var fullScreenPendingIntent = PendingIntent.GetActivity (context, 0,
                intent, PendingIntentFlags.CancelCurrent);
                builder.SetContentText (message)
                       .SetFullScreenIntent (fullScreenPendingIntent, true)
                       .SetContentIntent (fullScreenPendingIntent);

            return builder.Build ();
        }
Beispiel #16
0
        public override void OnReceive(Context context, Intent intent)
        {
            //
            var notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService);

            //
            var resultIntent = new Intent(context, typeof(AfazerService));

            /*TaskStackBuilder stackBuilder = TaskStackBuilder.Create(context);
             * stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(AfazerService)));
             * stackBuilder.AddNextIntent(resultIntent);*/

            //
            //PendingIntent resultPendingIntent = stackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent);
            //
            var builder = new Notification.Builder(context);

            builder.SetAutoCancel(true);
            //builder.SetContentIntent(resultPendingIntent);
            builder.SetContentTitle(_title);
            builder.SetContentText(_description);
            builder.SetDefaults(NotificationDefaults.All);
            builder.SetSmallIcon(Resource.Drawable.icon);

            //
            notificationManager.Notify(100, builder.Build());
        }
Beispiel #17
0
        public async void Validate(string device, string correo, string contrasena)
        {
            string Result;
            var    ValidationResultTextView = FindViewById <TextView>(Resource.Id.ValidationResultTextView);
            var    Builder       = new Notification.Builder(this);
            var    ServiceClient = new SALLab07.ServiceClient();

            Console.WriteLine($"{correo} | {contrasena}");
            var SvcResult = await ServiceClient.ValidateAsync(
                correo,
                contrasena,
                device);

            Result = $"{SvcResult.Status}\n{SvcResult.Fullname}\n{SvcResult.Token}";

            if (Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
            {
                Builder.SetContentTitle("Resultado de la Validación");
                Builder.SetContentText(Result);
                Builder.SetSmallIcon(Resource.Drawable.Icon);
                Builder.SetCategory(Notification.CategoryMessage);

                var ObjectNotification = Builder.Build();
                var Manager            = GetSystemService(
                    Android.Content.Context.NotificationService) as NotificationManager;
                Manager.Notify(0, ObjectNotification);
            }
            else
            {
                ValidationResultTextView.Text = Result;
            }
        }
        private void Btn_edit_Click(object sender, EventArgs e)
        {
            if (notyBuilder == null)
            {
                Toast.MakeText(this, "هیچ نوتیفیکیشنی وجود ندارد", ToastLength.Short).Show();
            }
            else
            {
                notyBuilder.SetContentTitle("Updated Notification");
                notyBuilder.SetContentText("Changed to this message.");


                #region InboxStyle

                var inboxStyle = new Notification.InboxStyle();
                inboxStyle.AddLine("hamed: Bananas on sale");
                inboxStyle.AddLine("nili: Curious about your blog post");
                inboxStyle.AddLine("saeed: Need a ride to Evolve?");
                inboxStyle.SetSummaryText("+8 more");

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

                #endregion
                var notification = notyBuilder.Build();
                var notyManager  = GetSystemService(Context.NotificationService) as NotificationManager;
                notyManager.Notify(notyId, notification);
            }
        }
Beispiel #19
0
        protected override void OnMessage(Context context, Intent intent)
        {
            Console.WriteLine("Received Notification");

            //Push Notification arrived - print out the keys/values
            if (intent != null || intent.Extras != null)
            {
                var keyset = intent.Extras.KeySet();

                foreach (var key in intent.Extras.KeySet())
                {
                    Console.WriteLine("Key: {0}, Value: {1}", key, intent.Extras.GetString(key));
                }

                var msg = intent.GetStringExtra("message");

                var n = new Notification.Builder(context);
                n.SetSmallIcon(Android.Resource.Drawable.IcDialogAlert);
                n.SetContentTitle("InFridge Expiration Notice");
                n.SetTicker(msg);
                n.SetContentText(msg);

                var nm = NotificationManager.FromContext(context);
                nm.Notify(0, n.Build());
            }
        }
        private void Button_Click(object sender, EventArgs e)
        {
            notyBuilder = new Notification.Builder(this);

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

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



            #region BigTextStyle

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

            #endregion

            #region InboxStyle

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

            notyBuilder.SetStyle(inboxStyle);

            #endregion

            #region imageStyle

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


            #endregion

            var notification = notyBuilder.Build();
            var notyManager  = GetSystemService(Context.NotificationService) as NotificationManager;
            notyManager.Notify(notyId, notification);
        }
        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);
            }
        }
Beispiel #22
0
 public override void OnCreate()
 {
     Notification.Builder builder = new Notification.Builder(ApplicationContext);
     builder.SetContentTitle("DSAMobile");
     builder.SetContentText("DSAMobile service is running");
     builder.SetOngoing(true);
     _serviceNotification = builder.Build();
 }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

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

            button1 = FindViewById <Button>(Resource.Id.button1);

            Notification.Builder builder             = new Notification.Builder(this);
            const int            notificationID      = 0;
            NotificationManager  notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;

            bool firstNotificationSent = false;


            button1.Click += delegate
            {
                if (!firstNotificationSent)
                {
                    // Notifications at a minimum have:   icon, title, message & time
                    builder.SetContentText("My app notification");
                    builder.SetContentText("Hi there this is a notification(obiviously)");
                    builder.SetSmallIcon(Resource.Mipmap.ic_home_black_24dp);  // see android documentation for icon sizes

                    // this is deprecated !!!!!!
                    builder.SetDefaults(NotificationDefaults.Sound | NotificationDefaults.Lights);

                    Notification notification = builder.Build();

                    // service that displays the notification
                    notificationManager.Notify(notificationID, notification);

                    firstNotificationSent = true;
                }
                else
                {
                    builder.SetContentTitle("Update to notification");
                    builder.SetContentText("Stop pressing the button!");

                    Notification notif = builder.Build();
                    notificationManager.Notify(notificationID, notif);
                }
            };
        }
Beispiel #24
0
 private void NotificationText(string text, string subtext)
 {
     notificationBuilder.SetContentText(text);
     if (!string.IsNullOrEmpty(subtext))
     {
         notificationBuilder.SetSubText(subtext);
     }
     notificationManager.Notify(NOTIFICATION_ID, notificationBuilder.Build());
 }
Beispiel #25
0
 public void notifier()
 {
     builder.SetContentText(disc_text.Text);
     builder.SetSmallIcon(Resource.Mipmap.ic_launcher);
     notify = builder.Build();
     notificationmanager = this.Activity.GetSystemService(Context.NotificationService) as NotificationManager;
     notificationmanager.Notify(notification_id, notify);
     disc_text.Text = "";
 }
        public void SentNoficationForNewInovoice(List <Customer> countNewНotifyNewInvoiceCustomers)
        {
            if (countNewНotifyNewInvoiceCustomers.Count > 0)
            {
                // Set up an intent so that tapping the notifications returns to this app:
                Intent intent = new Intent(this, typeof(MainActivity));

                // Create a PendingIntent;
                const int     pendingIntentId = 1;
                PendingIntent pendingIntent   =
                    PendingIntent.GetActivity(this, pendingIntentId, intent, PendingIntentFlags.OneShot);


                // Instantiate the Inbox style:
                Notification.InboxStyle inboxStyle = new Notification.InboxStyle();

                //  Instantiate the builder and set notification elements:
                Notification.Builder bulideer = new Notification.Builder(this);

                bulideer.SetContentIntent(pendingIntent);
                bulideer.SetSmallIcon(Resource.Drawable.vik);

                // Set the title and text of the notification:
                bulideer.SetContentTitle("Нова фактура");
                //  bulideer.SetContentText("*****@*****.**");

                foreach (var item in countNewНotifyNewInvoiceCustomers)
                {
                    // Generate a message summary for the body of the notification:

                    //  if(item.DidGetNewInoviceToday == false)
                    //  {
                    string money = item.MoneyToPay.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("bg-BG"));

                    inboxStyle.AddLine($"Аб. номер: {item.Nomer.ToString()}, {money}");

                    bulideer.SetContentText($"Аб. номер: {item.Nomer.ToString()}, {money}");

                    // item.DidGetNewInoviceToday = true;
                    //  }
                }
                // Plug this style into the builder:
                bulideer.SetStyle(inboxStyle);

                // Build the notification:
                Notification notification11 = bulideer.Build();

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

                // Publish the notification:
                const int notificationIdd = 1;
                notificationManager1.Notify(notificationIdd, notification11);
            }
        }
        public void CreateSimplestNotification()
        {
            CreateNotificationChannel();
            var builder = new Notification.Builder(_lastChannelId);

            builder.SetContentTitle("Simple");
            builder.SetContentText("Notification");
            builder.SetSmallIcon("notify_icon_small");
            Notify(builder);
        }
Beispiel #28
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

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

            sortingSpinner = FindViewById <Spinner>(Resource.Id.spinner1);

            tsumTsumDatabaseManager   = new TsumTsumDatabaseManager();
            tsumTsumBroadcastReceiver = new TsumTsumNotifcationBroadcastReceiver();

            toolbar = FindViewById <Toolbar>(Resource.Id.toolbar);
            SetActionBar(toolbar);
            ActionBar.Title = GetString(Resource.String.ApplicationNameShort);

            sortingSpinner.ItemSelected += delegate
            {
                Settings.SetInt("sortingType", sortingSpinner.SelectedItemPosition);
                UpdateHeartView();
            };

            StartNotificationServiceIfNotRunning();

            if (!IsNotificationPermissionSet())
            {
                CreateAlert(
                    "No Permission",
                    "The required permissions are not set, do you want to set the setting now?",
                    "Yes",
                    (object sender, DialogClickEventArgs args) => { StartActivityForResult(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"), 0); }, // BEFORE: Android.Provider.Settings.ActionNotificationListenerSettings
                    "No",
                    (object sender, DialogClickEventArgs args) => { } // Deliberately empty!
                    );
            }

            CheckVersion(null, () =>
            {
                CreateAlert(
                    "New version available",
                    "A new version of the app is available, do you want to download it now?",
                    "Yes",
                    (object sender, DialogClickEventArgs args) => { StartActivity(new Intent(Intent.ActionView, global::Android.Net.Uri.Parse("http://tsumtsumhearttracker.pleduc.nl/download/newest/nl.pleduc.TsumTsumNotificationTracker-Signed.apk"))); },
                    "No",
                    (object sender, DialogClickEventArgs args) => { } // Deliberately empty!
                    );
            });

            Notification.Builder notificationBuilder = new Notification.Builder(this);
            notificationBuilder.SetContentTitle("Test");
            notificationBuilder.SetContentText("Test2");
            notificationBuilder.SetSmallIcon(Resource.Drawable.Icon);
            Notification notification = notificationBuilder.Build();
        }
		// Creates a new notification with a different visibility level.
		public Notification CreateNotification(NotificationVisibility visibility)
		{
			var builder = new Notification.Builder (Activity)
				.SetContentTitle ("Notification for Visibility metadata");

			builder.SetVisibility (visibility);
			builder.SetContentText (string.Format ("Visibility : {0}", 
				NotificationVisibilities.GetDescription(visibility)));
			builder.SetSmallIcon (NotificationVisibilities.GetNotificationIconId (visibility));
			return builder.Build ();
		}
        // Creates a new notification with a different visibility level.
        public Notification CreateNotification(NotificationVisibility visibility)
        {
            var builder = new Notification.Builder(Activity)
                          .SetContentTitle("Notification for Visibility metadata");

            builder.SetVisibility(visibility);
            builder.SetContentText(string.Format("Visibility : {0}",
                                                 NotificationVisibilities.GetDescription(visibility)));
            builder.SetSmallIcon(NotificationVisibilities.GetNotificationIconId(visibility));
            return(builder.Build());
        }
Beispiel #31
0
        private void CheckServerNotifications(Context pContext, string sClan, string sName)
        {
            XElement pResponse = null;
            //try
            //{
            string sPrevClan = Master.GetActiveClan();
            string sPrevUser = Master.GetActiveUserName();

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

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

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

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

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

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

                    Notification        pNotif   = pBuilder.Build();
                    NotificationManager pManager = (NotificationManager)pContext.GetSystemService(Context.NotificationService);
                    pManager.Notify((int)Java.Lang.JavaSystem.CurrentTimeMillis(), pNotif);                     // using time to make different ID every time, so doesn't replace old notification
                    //pManager.Notify(DateTime.Now.Millisecond, pNotif); // using time to make different ID every time, so doesn't replace old notification
                }
            }
        }
        /// <summary>
        /// Show a local notification in the Notification Area and Drawer.
        /// </summary>
        /// <param name="title">Title of the notification</param>
        /// <param name="body">Body or description of the notification</param>
        public void Show(string title, string body)
        {
            var builder = new Notification.Builder(Application.Context);
            builder.SetContentTitle(title);
            builder.SetContentText(body);
            builder.SetSmallIcon(Resource.Drawable.Icon);

            var notification = builder.Build();

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

            manager.Notify(0, notification);
        }
Beispiel #33
0
        private void SendNotification(string title, string text, int resourceIconId)
        {
            Notification.Builder notificationBuilder = new Notification.Builder(this);
            notificationBuilder.SetContentTitle(title);
            notificationBuilder.SetContentText(text);
            notificationBuilder.SetSmallIcon(resourceIconId);

            Notification notification = notificationBuilder.Build();

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

            notificationManager.Notify(++internalNotificationId, notification);
        }
        private void SentNotificationForOverdue(List <Customer> countНotifyInvoiceOverdueCustomers)
        {
            if (countНotifyInvoiceOverdueCustomers.Count > 0)
            {
                string countНotifyInvoiceOverdueCustomersAsString = JsonConvert.SerializeObject(countНotifyInvoiceOverdueCustomers);

                // Set up an intent so that tapping the notifications returns to this app:
                Intent intent = new Intent(this, typeof(MainActivity));

                // Create a PendingIntent;
                const int     pendingIntentId = 0;
                PendingIntent pendingIntent   =
                    PendingIntent.GetActivity(this, pendingIntentId, intent, PendingIntentFlags.OneShot);

                // Instantiate the Inbox style:
                Notification.InboxStyle inboxStyle = new Notification.InboxStyle();

                //  Instantiate the builder and set notification elements:
                Notification.Builder bulideer = new Notification.Builder(this)
                                                .SetContentIntent(pendingIntent)
                                                .SetSmallIcon(Resource.Drawable.vik);

                // Set the title and text of the notification:
                bulideer.SetContentTitle("Просрочване");

                foreach (var item in countНotifyInvoiceOverdueCustomers)
                {
                    // Generate a message summary for the body of the notification:

                    string format = "dd.MM.yyyy";
                    string date   = item.EndPayDate.ToString(format);

                    inboxStyle.AddLine($"Аб. номер: {item.Nomer.ToString()}, {date}");

                    bulideer.SetContentText($"Аб. номер: {item.Nomer.ToString()}, {date}");
                }
                // Plug this style into the builder:
                bulideer.SetStyle(inboxStyle);

                // Build the notification:
                Notification notification11 = bulideer.Build();

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

                // Publish the notification:
                const int notificationIdd = 0;
                notificationManager1.Notify(notificationIdd, notification11);
            }
        }
        public void SentNotificationForReading(List <Customer> countНotifyReadingustomers)
        {
            if (countНotifyReadingustomers.Count > 0)
            {
                // Set up an intent so that tapping the notifications returns to this app:
                Intent intent = new Intent(this, typeof(MainActivity));

                // Create a PendingIntent;
                const int     pendingIntentId = 2;
                PendingIntent pendingIntent   =
                    PendingIntent.GetActivity(this, pendingIntentId, intent, PendingIntentFlags.CancelCurrent);


                // Instantiate the Inbox style:
                Notification.InboxStyle inboxStyle = new Notification.InboxStyle();

                //  Instantiate the builder and set notification elements:
                Notification.Builder bulideer = new Notification.Builder(this);

                bulideer.SetSmallIcon(Resource.Drawable.vik);
                bulideer.SetContentIntent(pendingIntent);

                // Set the title and text of the notification:
                bulideer.SetContentTitle("Ден на отчитане");

                foreach (var cus in countНotifyReadingustomers)
                {
                    // Generate a message summary for the body of the notification:
                    string format = "dd.MM.yyyy";
                    string date   = cus.StartReportDate.ToString(format);

                    inboxStyle.AddLine($"Аб. номер: {cus.Nomer.ToString()}, {date}");

                    bulideer.SetContentText($"Аб. номер: {cus.Nomer.ToString()}, {date}");
                }

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

                // Build the notification:
                Notification notification11 = bulideer.Build();

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

                // Publish the notification:
                const int notificationIdd = 2;
                notificationManager1.Notify(notificationIdd, notification11);
            }
        }
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);


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

            txtView = (TextView)FindViewById(Resource.Id.tbNotificationInfo);
            //txtView = (TextView)FindViewById(Resource.Id.textView1);
            nReceiver = new NotificationReceiver();
            IntentFilter filter = new IntentFilter();
            filter.AddAction("com.dpwebdev.handsetfree.NOTIFICATION_LISTENER_EXAMPLE");
            RegisterReceiver(nReceiver, filter);

            // Get our button from the layout resource,
            // and attach an event to it
            Button createButton = FindViewById<Button>(Resource.Id.MyButton);
            Button catchButton = FindViewById<Button>(Resource.Id.catchNotification);

            createButton.Click += delegate
            {
                NotificationManager nManager = (NotificationManager)GetSystemService(NotificationListenerService.NotificationService);
                Notification.Builder ncomp = new Notification.Builder(this);
                ncomp.SetContentTitle("My Notification");
                ncomp.SetContentText("Notification Listener Service Example");
                ncomp.SetTicker("Notification Listener Service Example");
                ncomp.SetSmallIcon(Resource.Drawable.Icon);
                ncomp.SetAutoCancel(true);
                nManager.Notify(DateTime.Now.Millisecond, ncomp.Build());

                

            };

            catchButton.Click += delegate
            {
                
                Intent i = new Intent("com.dpwebdev.handsetfree.NOTIFICATION_LISTENER_SERVICE_EXAMPLE");
                i.PutExtra("command", "list");
                SendBroadcast(i);
            };

        }
		// Creates a new notification depending on makeHeadsUpNotification.
		// If makeHeadsUpNotification is true, the notifications will be
		// Heads-Up Notifications.
		public Notification CreateNotification(bool makeHeadsUpNotification)
		{
			var builder = new Notification.Builder (Activity)
				.SetSmallIcon (Resource.Drawable.ic_launcher_notification)
				.SetPriority ((int) NotificationPriority.Default)
				.SetCategory (Notification.CategoryMessage)
				.SetContentTitle ("Sample Notification")
				.SetContentText ("This is a normal notification.");
			if (makeHeadsUpNotification) {
				var push = new Intent ();
				push.AddFlags (ActivityFlags.NewTask);
				push.SetClass (Activity, Java.Lang.Class.FromType (typeof(MainActivity)));
				var fullScreenPendingIntent = PendingIntent.GetActivity (Activity, 0,
					push, PendingIntentFlags.CancelCurrent);
				builder
					.SetContentText ("Heads-Up Notification on Android L or above.")
					.SetFullScreenIntent (fullScreenPendingIntent, true);
			}
			return builder.Build ();
		}
Beispiel #38
0
        void SendNotification(MessaggioNotifica m)
        {
            var intent = new Intent (this, typeof(MainActivity));

            intent.AddFlags (ActivityFlags.ClearTop);

            var notifica = new Notification.Builder (this);
            switch (m.Tipo) {
            case "1":
                notifica.SetSmallIcon (Resource.Drawable.alert_1);
                break;
            case "2":
                notifica.SetSmallIcon (Resource.Drawable.alert_2);
                break;
            case "3":
                notifica.SetSmallIcon (Resource.Drawable.alert_3);
                break;
            default:
                notifica.SetSmallIcon (Resource.Drawable.InvioDoc);
                break;
            }

            if (m.Tipo == "4") {
                Messaggio mess = new Messaggio (m.Titolo, m.Messaggio);
                intent.PutExtra ("messaggio", JsonConvert.SerializeObject(mess));
            } else {
                intent.PutExtra ("commessanum", m.Commessa);
            }
            var pendingIntent = PendingIntent.GetActivity (this, 0, intent, PendingIntentFlags.OneShot);

            notifica.SetContentTitle (m.Titolo);
            notifica.SetContentText (m.Messaggio);
            notifica.SetAutoCancel (true);
            notifica.SetContentInfo (m.Commessa);
            notifica.SetSubText ("Commessa " + m.Commessa);
            notifica.SetVibrate (new long[] {100,200,100});
            notifica.SetSound (RingtoneManager.GetDefaultUri(RingtoneType.Notification));
            notifica.SetContentIntent (pendingIntent);
            var notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);
            notificationManager.Notify (0, notifica.Build());
        }
		private static void ShowNativeNotification(Common.Message message, string notificationId, ButtonSet buttonSet = null, string alertTextOverride = null)
		{
			var nativeNotificationId = new Random().Next();

			// Setup intent to launch application
			var context = Application.Context;

			// Build the notification
			var builder = new Notification.Builder(context)
				.SetContentTitle(message.SenderDisplayName)
				.SetSmallIcon(Resource.Drawable.donky_notification_small_icon_simple_push)
				.SetContentText(alertTextOverride ?? message.Body)
				.SetVibrate(new[] { 0L, 100L })
			    .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification));

			var pushMessage = message as SimplePushMessage;
			if (pushMessage != null && buttonSet != null && buttonSet.ButtonSetActions.Any())
			{
				builder.SetAutoCancel(false);
				// Jelly Bean + above supports multiple actions
				if (buttonSet.ButtonSetActions.Count == 2
				    && Build.VERSION.SdkInt >= BuildVersionCodes.JellyBean)
				{
					foreach (var action in buttonSet.ButtonSetActions)
					{
						builder.AddAction(0,
							action.Label,
							CreateIntentForAction(context, nativeNotificationId, 
								notificationId, action, pushMessage,
								buttonSet));
					}
				}
				else
				{
					builder.SetContentIntent(CreateIntentForAction(context, nativeNotificationId, 
						notificationId, buttonSet.ButtonSetActions[0], 
						pushMessage, buttonSet));
				}
			}
			else
			{
				var intent = CreateIntentForBasicPush(context, nativeNotificationId, notificationId);
				builder.SetContentIntent(intent)
					.SetAutoCancel(true);
			}

            // bug
            if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
            {
                builder.SetCategory(Notification.CategoryMessage)
                    .SetPriority((int) NotificationPriority.High)
                    .SetVisibility(NotificationVisibility.Public);

                // this is for a Heads-Up Notification (Out of App Notification)
                var push = new Intent();
                push.AddFlags(ActivityFlags.NewTask);
                push.SetClass(context, Java.Lang.Class.FromType(context.GetType()));
                var fullScreenPendingIntent = PendingIntent.GetActivity(context, 0,
                    push, PendingIntentFlags.CancelCurrent);
                builder
                    .SetContentText(alertTextOverride ?? message.Body)
                    .SetFullScreenIntent(fullScreenPendingIntent, true);

            }

			var notification = builder.Build();

			notification.LedARGB = Color.White;
			notification.Flags |= NotificationFlags.ShowLights;
			notification.LedOnMS = 200;
			notification.LedOffMS = 2000;

			var notificationManager = (NotificationManager) context.GetSystemService(Context.NotificationService);
			notificationManager.Notify(nativeNotificationId, notification);
		}
        /// <summary>
        /// Update the notification.
        /// </summary>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <returns>
        /// The updated notification.
        /// </returns>
        public Notification UpdateNotification(Context context)
        {
            var builder = new Notification.Builder(context);
            if (!string.IsNullOrEmpty(this.PausedText))
            {
                builder.SetContentTitle(this.PausedText);
                builder.SetContentText(string.Empty);
                builder.SetContentInfo(string.Empty);
            }
            else
            {
                builder.SetContentTitle(this.Title);
                if (this.TotalBytes > 0 && this.CurrentBytes != -1)
                {
                    builder.SetProgress((int)(this.TotalBytes >> 8), (int)(this.CurrentBytes >> 8), false);
                }
                else
                {
                    builder.SetProgress(0, 0, true);
                }

                builder.SetContentText(Helpers.GetDownloadProgressString(this.CurrentBytes, this.TotalBytes));
                builder.SetContentInfo(string.Format("{0}s left", Helpers.GetTimeRemaining(this.TimeRemaining)));
            }

            builder.SetSmallIcon(this.Icon != 0 ? this.Icon : Android.Resource.Drawable.StatSysDownload);
            builder.SetOngoing(true);
            builder.SetTicker(this.Ticker);
            builder.SetContentIntent(this.PendingIntent);

            return builder.Notification;
        }
		public override void OnMessageReceived (IMessageEvent messageEvent)
		{
			string path = messageEvent.Path;
			if (path.Equals (Constants.QUIZ_EXITED_PATH)) {
				((NotificationManager)GetSystemService (NotificationService)).CancelAll ();
			}
			if (path.Equals (Constants.QUIZ_ENDED_PATH) || path.Equals (Constants.QUIZ_EXITED_PATH)) {
				var dataMap = DataMap.FromByteArray (messageEvent.GetData ());
				int numCorrect = dataMap.GetInt (Constants.NUM_CORRECT);
				int numIncorrect = dataMap.GetInt (Constants.NUM_INCORRECT);
				int numSkipped = dataMap.GetInt (Constants.NUM_SKIPPED);

				var builder = new Notification.Builder (this)
					.SetContentTitle (GetString (Resource.String.quiz_report))
					.SetSmallIcon (Resource.Drawable.ic_launcher)
					.SetLocalOnly (true);
				var quizReportText = new SpannableStringBuilder ();
				AppendColored (quizReportText, numCorrect.ToString (), Resource.Color.dark_green);
				quizReportText.Append (" " + GetString (Resource.String.correct) + "\n");
				AppendColored (quizReportText, numIncorrect.ToString (), Resource.Color.dark_red);
				quizReportText.Append (" " + GetString (Resource.String.incorrect) + "\n");
				AppendColored (quizReportText, numSkipped.ToString (), Resource.Color.dark_yellow);
				quizReportText.Append (" " + GetString (Resource.String.skipped) + "\n");

				builder.SetContentText (quizReportText);
				if (!path.Equals (Constants.QUIZ_EXITED_PATH)) {
					builder.AddAction (Resource.Drawable.ic_launcher,
						GetString (Resource.String.reset_quiz), GetResetQuizPendingIntent ());
				}
				((NotificationManager)GetSystemService (NotificationService))
					.Notify (QUIZ_REPORT_NOTIF_ID, builder.Build ());
			}
		}
Beispiel #42
0
        /// <summary>
        /// When we start on the foreground we will present a notification to the user
        /// When they press the notification it will take them to the main page so they can control the music
        /// </summary>
        void StartForeground ()
        {
            var intent = new Intent (ApplicationContext, typeof (MainActivity));
            intent.SetAction (Intent.ActionMain);
            intent.AddCategory (Intent.CategoryLauncher);
            ExtraUtils.PutSelectedTab (intent, (int) MainActivity.TabTitle.Player);

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

            var notificationBuilder = new Notification.Builder (ApplicationContext);
            notificationBuilder.SetContentTitle (CurrentEpisode.Title);
            notificationBuilder.SetContentText (
                String.Format (
                    ApplicationContext.GetString (Resource.String.NotificationContentText),
                    ApplicationContext.GetString (Resource.String.ApplicationName)
                )
            );
            notificationBuilder.SetSmallIcon (Resource.Drawable.ic_stat_av_play_over_video);
            notificationBuilder.SetTicker (
                String.Format (
                    Application.GetString (Resource.String.NoticifationTicker),
                    CurrentEpisode.Title
                )
            );
            notificationBuilder.SetOngoing (true);
            notificationBuilder.SetContentIntent (pendingIntent);

            StartForeground (NotificationId, notificationBuilder.Build());
        }
        public void UpdateNetworkStatus() {
            try
            {
                ActivityController++;
                _state = DataAccessLayer.NetworkState.Unknown;

                // Retrieve the connectivity manager service
                var connectivityManager = (ConnectivityManager)
                    Application.Context.GetSystemService (
                        Context.ConnectivityService);

                // Check if the network is connected or connecting.
                // This means that it will be available, 
                // or become available in a few seconds.
                var activeNetworkInfo = connectivityManager.ActiveNetworkInfo;

                Android.Content.Res.Resources res = _activity.Resources;
                NotificationManager notificationManager = (NotificationManager) _activity.GetSystemService (
                    Android.Content.Context.NotificationService);

                Android.Net.Uri uri = null;


                if (activeNetworkInfo == null)
                {

                    // Send the two notification: 
                    // 1. There is no connection.
                    // 2. The user is offline

                    if (ActivityController > 1)
                        uri = Android.Media.RingtoneManager.GetDefaultUri ( Android.Media.RingtoneType.Notification);

                    Notification.Builder builder = new Notification.Builder (_activity)
                        .SetSmallIcon (Resource.Drawable.ic_network_disconnected)
                        .SetAutoCancel (false)
                        .SetSound (uri)
                        //.SetVibrate (new long[] { 1000, 1000, 1000, 1000, 1000 })
                        .SetLights (54, 3000, 5)
                        .SetContentText ( _activity.Resources.GetString(Resource.String.NetworkDisconnected))
                        .SetContentTitle (_activity.Resources.GetString(Resource.String.AppName)  + " - "  +  _activity.Resources.GetString(Resource.String.Disconnected))
                        .SetContentIntent (GetDialogPendingIntent ())
                        .SetTicker (_activity.Resources.GetString(Resource.String.Disconnected));
                    Notification notification = builder.Build();
                    notificationManager.Notify (1, notification);

                    builder = new Notification.Builder (_activity)
                        .SetSmallIcon (UI.Resource.Drawable.ic_action_offline)
                        .SetAutoCancel (false)
                        .SetSound (Android.Media.RingtoneManager.GetDefaultUri ( Android.Media.RingtoneType.Notification))
                        .SetLights (54,3000,5)
                        .SetContentText ( _activity.Resources.GetString(Resource.String.UserOffline))
                        .SetContentTitle (_activity.Resources.GetString(Resource.String.AppName)  + " - "  + "Offline")
                        .SetTicker (_activity.Resources.GetString(Resource.String.UserOffline));
                    notification = builder.Build();
                    notificationManager = (NotificationManager) _activity.GetSystemService (
                        Android.Content.Context.NotificationService);
                    notificationManager.Notify (2, notification);


                    /*AlertDialog a = new  AlertDialog.Builder (this)
                            .SetTitle ("NETWORK")
                            .SetMessage ("No Network")
                            .SetPositiveButton (Android.Resource.String.Ok, delegate (object o, DialogClickEventArgs e) {})
                            .Create();
                        a.Show ();*/
                    _state =  DataAccessLayer.NetworkState.Disconnected;
                    return;
                }

                if (activeNetworkInfo.IsConnectedOrConnecting) {

                    if (ActivityController > 1)
                        uri = Android.Media.RingtoneManager.GetDefaultUri ( Android.Media.RingtoneType.Notification);

                    Notification.Builder builder = new Notification.Builder (_activity)
                        .SetSmallIcon (UI.Resource.Drawable.ic_network_connected)
                        .SetAutoCancel (false)
                        .SetSound (uri)

                        //.SetVibrate (new long[] { 10, 0 })
                        .SetLights (54,3000,5)
                        .SetContentTitle (_activity.Resources.GetString(Resource.String.AppName)  + " - "  + _activity.Resources.GetString(Resource.String.Connected))
                        .SetContentIntent (GetDialogPendingIntent ())
                        .SetTicker (_activity.Resources.GetString(Resource.String.Connected));



                    //.SetContentIntent (GetDialogPendingIntent ("Connected."));

                    // According to the status of the user, adjust the text of the notification
                    if (MainActivity.User.NetworkStatus == DataAccessLayer.NetworkState.Disconnected)
                        builder.SetContentText( _activity.Resources.GetString(Resource.String.NetworkConnected));
                    else
                        builder.SetContentText( _activity.Resources.GetString(Resource.String.NetworkConnected));

                    Notification notification = builder.Build();

                    notificationManager.Notify (1, notification);

                    // Now that we know it's connected, determine if we're on WiFi or something else.
                    _state = activeNetworkInfo.Type == ConnectivityType.Wifi ?
                        DataAccessLayer.NetworkState.ConnectedWifi : DataAccessLayer.NetworkState.ConnectedData;

                    // First check if there is any unsync data in the SQLite database
                    offlineTasks =  BusinessLayer.Task.HasNewOfflineTasks();

                    // If there is and the user is online then ask for synchronizing the data
                    if (offlineTasks != 0 &&MainActivity.User.NetworkStatus  != DataAccessLayer.NetworkState.Disconnected)
                    {
                        // Ask the user if he wants to upload the unsynchronized data
                        var alertdialog = new AlertDialog.Builder(this._activity);
                        alertdialog.SetIconAttribute(Android.Resource.Attribute.AlertDialogIcon);
                        alertdialog.SetTitle(Resource.String.OfflineData);
                        alertdialog.SetPositiveButton(Resource.String.Yes, OfflineDataYesClicked);
                        alertdialog.SetNegativeButton(Resource.String.No, OfflineDataNoClicked);

                        // Set the right Message
                        if (offlineTasks == 1)
                            alertdialog.SetMessage(string.Format(_activity.GetString(Resource.String.AskUpload), offlineTasks));
                        else
                            alertdialog.SetMessage(string.Format(_activity.GetString(Resource.String.AskUploads), offlineTasks));
                        alertdialog.Show();
                    }


                } 
                else 
                {

                    if (ActivityController > 1)
                        uri = Android.Media.RingtoneManager.GetDefaultUri ( Android.Media.RingtoneType.Notification);

                    // Send the two notification: 
                    // 1. There is no connection.
                    // 2. The user is offline

                    Notification.Builder builder = new Notification.Builder (_activity)

                        .SetSmallIcon (UI.Resource.Drawable.ic_network_disconnected)
                        .SetAutoCancel (false)
                        .SetSound (uri)
                        //.SetVibrate (new long[] { 1000, 1000, 1000, 1000, 1000 })
                        .SetLights (54, 3000, 5)
                        .SetContentText (_activity.Resources.GetString(Resource.String.NetworkDisconnected))
                        .SetContentTitle (_activity.Resources.GetString(Resource.String.AppName)  + " - "  + _activity.Resources.GetString(Resource.String.Disconnected))
                        .SetContentIntent (GetDialogPendingIntent ())
                        .SetTicker (_activity.Resources.GetString(Resource.String.Disconnected));
                    //.SetContentIntent (GetDialogPendingIntent ("Disconnected"));

                    Notification notification = builder.Build();

                    notificationManager.Notify (1, notification);


                    builder = new Notification.Builder (_activity)
                        .SetSmallIcon (UI.Resource.Drawable.ic_action_offline)
                        .SetAutoCancel (false)
                        .SetSound (Android.Media.RingtoneManager.GetDefaultUri ( Android.Media.RingtoneType.Notification))
                        .SetLights (54,3000,5)
                        .SetContentText ( _activity.Resources.GetString(Resource.String.UserOffline))
                        .SetContentTitle (_activity.Resources.GetString(Resource.String.AppName)  + " - "  + "Offline")
                        .SetTicker (_activity.Resources.GetString(Resource.String.UserOffline));
                    notification = builder.Build();
                    notificationManager = (NotificationManager) _activity.GetSystemService (
                        Android.Content.Context.NotificationService);
                    notificationManager.Notify (2, notification);


                    /*AlertDialog a = new  AlertDialog.Builder (this)
                            .SetTitle ("NETWORK")
                            .SetMessage ("Disconnected")
                            .SetPositiveButton (Android.Resource.String.Ok, delegate (object o, DialogClickEventArgs e) {})
                            .Create();*/

                    _state = DataAccessLayer.NetworkState.Disconnected;
                }
            }
            catch(Exception ex)
            {
                DataAccessLayer.ExceptionWriter.WriteLogFile(ex);
            }


        }
        //reads msgs from api every 3 sec
        private void getMsgs()
        {
            var thread = new Thread(async () =>
             {
                 MyMessage[] msgs;

                 Notification.Builder builder = new Notification.Builder(this)
                 .SetAutoCancel(true)
                 .SetSmallIcon(Resource.Drawable.notif)
                 .SetDefaults(NotificationDefaults.Sound);

                 var nMgr = (NotificationManager)GetSystemService(NotificationService);

                 Notification notification = new Notification(Resource.Drawable.notif, "message notification");

                 Intent intent = new Intent(this, typeof(ChatActivity));
                 PendingIntent pendingIntent;
                 ViewModel myViewModel = ViewModel.myViewModelInstance;

                 while (true)
                 {

                     string result = await ApiRequests.getMessages(MapActivity.client);
                     msgs = JsonConvert.DeserializeObject<MyMessage[]>(result);

                     if (notifCounter == 0)
                     {
                         for (int i = msgs.Length-1; i >=0; --i)
                         {
                             MyMessage msg = msgs[i];

                             if (!myViewModel.msgContainer.ContainsKey(msg.message_id))
                             {
                                 myViewModel.msgContainer.Add(msg.message_id, msg);
                                 myViewModel.msgsContainer.Add(msg);
                             }

                         }
                         notifCounter++;
                     }
                     else
                     {
                         for (int i = msgs.Length-1; i >= 0; --i)
                         {
                             MyMessage msg = msgs[i];
                             if (!myViewModel.msgContainer.ContainsKey(msg.message_id))
                             {

                                 myViewModel.msgContainer.Add(msg.message_id, msg);
                                 myViewModel.msgsContainer.Add(msg);

                                 if (msg.msg_type.Equals("from"))
                                 {
                                     intent.PutExtra("email", msg.email);
                                     intent.PutExtra("firstName", msg.first_name);
                                     intent.PutExtra("lastName", msg.last_name);

                                     stackBuilder = Android.App.TaskStackBuilder.Create(this);
                                     stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(MapActivity)));
                                     stackBuilder.AddNextIntent(intent);

                                     pendingIntent = PendingIntent.GetActivity(this, notifCounter++, intent, PendingIntentFlags.OneShot);
                                     builder.SetContentIntent(pendingIntent);
                                     builder.SetContentTitle(msg.first_name + " " + msg.last_name);
                                     builder.SetContentText(msg.message);

                                     nMgr.Notify(notifCounter++, builder.Build());

                                     BroadcastStarted(msg);
                                 }
                             }
                         }

                     }
                     Thread.Sleep(3000);
                 }

             });

            thread.Start();
        }
Beispiel #45
0
        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            base.OnStartCommand(intent, flags, startId);

            var notificationIntent = new Intent(BaseContext, typeof(MainActivity));
            notificationIntent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop);
            var notifPendingIntent = PendingIntent.GetActivity(BaseContext, 0, notificationIntent, PendingIntentFlags.UpdateCurrent);
            var notif = new Notification
            {
                ContentIntent = notifPendingIntent
            };

            Notification.Builder notifBuilder = new Notification.Builder(BaseContext);
            notifBuilder.SetContentIntent(notifPendingIntent);
            notifBuilder.SetWhen(JavaSystem.CurrentTimeMillis());
            notifBuilder.SetSmallIcon(Resource.Drawable.Knock);
            notifBuilder.SetContentTitle(Resources.GetString(Resource.String.ApplicationName));
            notifBuilder.SetContentText(Resources.GetString(Resource.String.NotifText));

            StartForeground(Process.MyPid(), notifBuilder.Build());
            
            //var notificationManager = (NotificationManager) BaseContext.GetSystemService(NotificationService);
            //notificationManager.Notify(Process.MyPid(), new Notification { ContentIntent = notifPendingIntent });

            RegisterListener();

            _wakeLockPartial?.Acquire();

            Status = ServiceStatus.STARTED;
            Log.Debug("WakeUpService", "Service start command.");
            return StartCommandResult.StickyCompatibility;
        }