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); } }
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()); }
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); }
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); }
private void SendNotification(CorsoGiornaliero l) { System.Diagnostics.Debug.WriteLine("SEND NOTIFICATION"); // Set up an intent so that tapping the notifications returns to this app: Intent intent = new Intent(this, typeof(MainActivity)); // Create a PendingIntent; we're only using one PendingIntent (ID = 0): const int pendingIntentId = 0; PendingIntent pendingIntent = PendingIntent.GetActivity(this, pendingIntentId, intent, PendingIntentFlags.UpdateCurrent); Notification.Builder builder = new Notification.Builder(this) .SetContentIntent(pendingIntent) .SetContentTitle(l.Note.ToUpper()) .SetContentText(l.Insegnamento + " - " + l.Ora) .SetSmallIcon(Resource.Drawable.UnibgOk); //builder.SetStyle(new Notification.BigTextStyle().BigText(longMess)); Notification.InboxStyle inboxStyle = new Notification.InboxStyle(); inboxStyle.AddLine(l.Insegnamento); inboxStyle.AddLine(l.AulaOra); inboxStyle.AddLine(l.Docente); builder.SetStyle(inboxStyle); // Build the notification: Notification notification = builder.Build(); // Get the notification manager: NotificationManager notificationManager = this.GetSystemService(Context.NotificationService) as NotificationManager; // Publish the notification: const int notificationId = 1; notificationManager.Notify(notificationId, notification); }
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); } }
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); }
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); } }
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 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); }
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()); } }
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 } } }
/* * Submit user-interactive notification (not finished) */ public void SendExpandedNotification(DigitalCity.Model.Notification notification) { var title = notification.title; var content = notification.content; var image = notification.imagePath; var id = notification.GetId(); Notification.Builder builder = CreateNotificationBuilder(title, content); int imageID = (int)typeof(Resource.Drawable).GetField(image).GetRawConstantValue(); builder.SetStyle(new Notification.BigPictureStyle().BigPicture(BitmapFactory.DecodeResource(CrossCurrentActivity.Current.Activity.Resources, imageID))); PublishNotification(builder, id); }
public void SendNotification(CorsoGiornaliero l) { if (!Settings.Notify) { return; } // Logcat.Write("SEND NOTIFICATION"); Logcat.Write("Creazione Notifica"); Logcat.WriteDB(_db, "Creazione notifica"); Logcat.WriteDB(_db, l.Note.ToUpper() + l.Insegnamento + " - " + l.Date.ToShortDateString() + " - " + l.Ora); // Set up an intent so that tapping the notifications returns to this app: var context = Android.App.Application.Context; //var context = Forms.Context; Intent intent = new Intent(context, typeof(MainActivity)); Logcat.WriteDB(_db, "Intent created"); // Create a PendingIntent; we're only using one PendingIntent (ID = 0): const int pendingIntentId = 0; PendingIntent pendingIntent = PendingIntent.GetActivity(context, pendingIntentId, intent, PendingIntentFlags.UpdateCurrent); Logcat.WriteDB(_db, "PendingIntent created"); Notification.Builder builder = new Notification.Builder(context) .SetContentIntent(pendingIntent) .SetContentTitle(l.Note.ToUpper()) .SetContentText(l.Insegnamento + " - " + l.Date.ToShortDateString() + " - " + l.Ora) .SetSmallIcon(Resource.Drawable.ic_notification_school) .SetAutoCancel(true); //builder.SetStyle(new Notification.BigTextStyle().BigText(longMess)); Notification.InboxStyle inboxStyle = new Notification.InboxStyle(); inboxStyle.AddLine(l.Insegnamento); inboxStyle.AddLine(l.Date.DayOfWeek + ", " + l.Date.ToShortDateString()); inboxStyle.AddLine(l.AulaOra); inboxStyle.AddLine(l.Docente); builder.SetStyle(inboxStyle); // 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 = 1; var rnd = new System.Random(); notificationManager.Notify(rnd.Next(), 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); } }
/// <summary> /// native android implementation to send notifications /// </summary> /// <param name="title"></param> /// <param name="description"></param> /// <param name="iconID"></param> /// <param name="entrys"></param> /// <param name="pluginName"></param> public void SendLocalNotification(string title, string description, int iconID, List <string> entrys, string pluginName) { var context = Xamarin.Forms.Forms.Context; var manager = (NotificationManager)context.GetSystemService(Context.NotificationService) as NotificationManager; var intent = context.PackageManager.GetLaunchIntentForPackage(context.PackageName); intent.PutExtra("PluginName", pluginName); // Create a PendingIntent; we're only using one PendingIntent (ID = 0): const int pendingIntentId = 0; PendingIntent pendingIntent = PendingIntent.GetActivity(context, 0, intent, PendingIntentFlags.CancelCurrent); // Instantiate the builder and set notification elements: Notification.Builder builder = new Notification.Builder(Android.App.Application.Context) .SetContentIntent(pendingIntent) .SetContentTitle(title) .SetContentText(description) .SetSmallIcon(Resource.Drawable.icon); // Instantiate the Inbox style: Notification.InboxStyle inboxStyle = new Notification.InboxStyle(); entrys.ForEach(x => inboxStyle.AddLine(x)); // Generate a message summary for the body of the notification: //inboxStyle.SetSummaryText("+2 more"); // Plug this style into the builder: builder.SetStyle(inboxStyle); // Build the notification: Notification notification = builder.Build(); // Publish the notification: const int notificationId = 0; manager.Notify(0, notification); }
public void SentNotificationWithoutSubscribe(Message newMessage) { // 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 = 3; 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 newMessage.Messages) { // Generate a message summary for the body of the notification: inboxStyle.AddLine($"{item.ToString()}"); bulideer.SetContentText($"{item.ToString()}"); } // 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 = 3; notificationManager1.Notify(notificationIdd, notification11); }
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); }
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()); }
static void AddNotificationPdv(List <string> pdvs) { if (pdvs.Count > 0) { var intent = new Intent(context, typeof(MenuPdvs)); PendingIntent pendingIntent = PendingIntent.GetActivity(context, (int)TipoNotificacao.NovosPdvs, intent, PendingIntentFlags.OneShot); var builder = new Notification.Builder(context) .SetContentIntent(pendingIntent) .SetDefaults(NotificationDefaults.All) .SetSmallIcon(Resource.Drawable.logosmartpromoter); var inboxStyle = new Notification.InboxStyle(); builder.SetContentTitle(context.Resources.GetString(Resource.String.novos_pdvs, pdvs.Count)); if (pdvs.Count > 3) { inboxStyle.AddLine(pdvs[0]); inboxStyle.AddLine(pdvs[1]); inboxStyle.AddLine(pdvs[2]); inboxStyle.SetSummaryText(context.Resources.GetString(Resource.String.novos_pdvs, pdvs.Count - 3)); } else { foreach (var item in pdvs) { inboxStyle.AddLine(item); } } builder.SetStyle(inboxStyle); Notification notification = builder.Build(); var notificationManager = context.GetSystemService(Context.NotificationService) as NotificationManager; notificationManager.Notify((int)TipoNotificacao.NovosPdvs, notification); } }
public static void ShowNotification(Context context) { // Instantiate the builder and set notification elements: Notification.Builder builder = new Notification.Builder(context) .SetAutoCancel(true) .SetContentTitle("Sample Notification") .SetContentText("Hello World! This is my first notification!") .SetDefaults(NotificationDefaults.Sound | NotificationDefaults.Vibrate) .SetSmallIcon(Resource.Drawable.logo) .SetLargeIcon(BitmapFactory.DecodeResource(context.Resources, Resource.Drawable.logo)); builder.SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Ringtone)); // Setup an intent for SecondActivity: Intent secondIntent = new Intent(context, typeof(UserNotification)); // Pass some information to SecondActivity: secondIntent.PutExtra("message", "Greetings from MainActivity!"); // Create a task stack builder to manage the back stack: TaskStackBuilder stackBuilder = TaskStackBuilder.Create(context); // Add all parents of SecondActivity to the stack: stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(UserNotification))); // Push the intent that starts SecondActivity onto the stack: stackBuilder.AddNextIntent(secondIntent); // Obtain the PendingIntent for launching the task constructed by // stackbuilder. The pending intent can be used only once (one shot): const int pendingIntentId = 0; PendingIntent pendingIntent = stackBuilder.GetPendingIntent(pendingIntentId, PendingIntentFlags.OneShot); int totalunread = 10; if (totalunread > 0) { // Instantiate the Inbox style: Notification.InboxStyle inboxStyle = new Notification.InboxStyle(); // Set the title and text of the notification: builder.SetContentIntent(pendingIntent); builder.SetContentTitle(totalunread + " new messages"); builder.SetContentText("WMS Trips"); //if (dtNotify.Rows.Count > 3) //{ // for (int i = 0; i < dtNotify.Rows.Count; i++) // { // if (i == 3) // { // i = int.MaxValue; // break; // } // else // { // inboxStyle.AddLine(string.Format("{0}: {1}", dtNotify.Rows[i]["Title"].ToString(), dtNotify.Rows[i]["Description"].ToString())); // } // } // inboxStyle.SetSummaryText("+"+(dtNotify.Rows.Count - 3) + " more"); //} //else //{ // for (int i = 0; i < dtNotify.Rows.Count; i++) // { // inboxStyle.AddLine(string.Format("{0}: {1}", dtNotify.Rows[i]["Title"].ToString(), dtNotify.Rows[0]["Description"].ToString())); // } //} // Plug this style into the builder: builder.SetStyle(inboxStyle); // 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); } }
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.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.SetSmallIcon(Resource.Drawable.vik); bulideer.SetContentIntent(pendingIntent); // Set the title and text of the notification: bulideer.SetContentTitle("Ден на отчитане"); foreach (var cus in countНotifyReadingustomers) { // if(cus.DidGetReadingToday == false) // { // 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}"); //cus.DidGetReadingToday = true; //cus.DidGetAnyNotificationToday = true; //Customer notifiedCustomer = mAllUpdateCustomerFromApi.FirstOrDefault(c => c.EGN == cus.EGN); //mAllUpdateCustomerFromApi.Remove(notifiedCustomer); //mAllUpdateCustomerFromApi.Add(cus); // } } //SaveCustomersFromApiInPhone(mAllUpdateCustomerFromApi); // 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); // ///// saveeeee // ISharedPreferences pref = //Application.Context.GetSharedPreferences("PREFERENCE_NAME", FileCreationMode.Private); // // convert the list to json // var listOfCustomersAsJson = JsonConvert.SerializeObject(mAllUpdateCustomerFromApi); // mCustomers // ISharedPreferencesEditor editor = pref.Edit(); // // set the value to Customers key // editor.PutString("Customers", listOfCustomersAsJson); // // commit the changes // editor.Commit(); } }
Notification CreateNotification() { LogHelper.Debug (Tag, "updateNotificationMetadata. mMetadata=" + metadata); if (metadata == null || playbackState == null) { return null; } var notificationBuilder = new Notification.Builder (service); int playPauseButtonPosition = 0; // If skip to previous action is enabled if ((playbackState.Actions & PlaybackState.ActionSkipToPrevious) != 0) { notificationBuilder.AddAction (Resource.Drawable.ic_skip_previous_white_24dp, service.GetString (Resource.String.label_previous), previousIntent); playPauseButtonPosition = 1; } AddPlayPauseAction (notificationBuilder); // If skip to next action is enabled if ((playbackState.Actions & PlaybackState.ActionSkipToNext) != 0) { notificationBuilder.AddAction (Resource.Drawable.ic_skip_next_white_24dp, service.GetString (Resource.String.label_next), nextIntent); } MediaDescription description = metadata.Description; var fetchArtUrl = string.Empty; Bitmap art = null; if (description.IconUri != null) { String artUrl = description.IconUri.ToString (); art = AlbumArtCache.Instance.GetBigImage (artUrl); if (art == null) { fetchArtUrl = artUrl; art = BitmapFactory.DecodeResource (service.Resources, Resource.Drawable.ic_default_art); } } notificationBuilder .SetStyle (new Notification.MediaStyle() .SetShowActionsInCompactView ( new []{ playPauseButtonPosition }) // show only play/pause in compact view .SetMediaSession (sessionToken)) .SetColor (notificationColor) .SetSmallIcon (Resource.Drawable.ic_notification) .SetVisibility (NotificationVisibility.Public) .SetUsesChronometer (true) .SetContentIntent (CreateContentIntent ()) .SetContentTitle (description.Title) .SetContentText (description.Subtitle) .SetLargeIcon (art); SetNotificationPlaybackState (notificationBuilder); if (fetchArtUrl != null) { FetchBitmapFromURL (fetchArtUrl, notificationBuilder); } return notificationBuilder.Build (); }
public void mostrarnotificacion() { List <PendingIntent> listapending = listapendingintents(); RemoteViews contentView = new RemoteViews(PackageName, Resource.Layout.layoutminiplayer); if (linkactual.Trim().Length > 1) { try { // contentView.SetImageViewBitmap(Resource.Id.imageView1, playeroffline.gettearinstancia().imageneses.First(info => info.GenerationId == playeroffline.gettearinstancia().diccionario[tituloactual])); contentView.SetImageViewBitmap(Resource.Id.fondo1, ImageHelper.CreateBlurredImageFromPortrait(this, 20, linkactual)); } catch (Exception) { } /// contentView.SetImageViewBitmap(Resource.Id.fondo1, clasesettings.CreateBlurredImageoffline(this, 20, linkactual)); } contentView.SetTextViewText(Resource.Id.textView1, tituloactual); contentView.SetOnClickPendingIntent(Resource.Id.imageView1, listapending[5]); contentView.SetOnClickPendingIntent(Resource.Id.imageView2, listapending[0]); contentView.SetOnClickPendingIntent(Resource.Id.imageView4, listapending[1]); contentView.SetOnClickPendingIntent(Resource.Id.imageView3, listapending[2]); contentView.SetOnClickPendingIntent(Resource.Id.imageView6, listapending[3]); contentView.SetOnClickPendingIntent(Resource.Id.imageView5, listapending[4]); Notification.Action accion1 = new Notification.Action(Resource.Drawable.playpause, "Playpause", listapending[0]); Notification.Action accion2 = new Notification.Action(Resource.Drawable.skipnext, "Siguiente", listapending[1]); Notification.Action accion3 = new Notification.Action(Resource.Drawable.skipprevious, "Anterior", listapending[2]); Notification.Action accion4 = new Notification.Action(Resource.Drawable.skipforward, "adelantar", listapending[3]); Notification.Action accion5 = new Notification.Action(Resource.Drawable.skipbackward, "atrazar", listapending[4]); /* * * 1-playpause * 2-siguiente * 3-anterior * 4-adelantar * 5-atrazar * */ Notification.MediaStyle estilo = new Notification.MediaStyle(); if (playeroffline.gettearinstancia() != null) { estilo.SetMediaSession(playeroffline.gettearinstancia().mSession.SessionToken); estilo.SetShowActionsInCompactView(1, 2, 3); } #pragma warning disable CS0618 // El tipo o el miembro están obsoletos var nBuilder = new Notification.Builder(this); #pragma warning restore CS0618 // El tipo o el miembro están obsoletos if (Build.VERSION.SdkInt < BuildVersionCodes.Lollipop) { #pragma warning disable 414 try { #pragma warning disable CS0618 // El tipo o el miembro están obsoletos nBuilder.SetContent(contentView); #pragma warning restore CS0618 // El tipo o el miembro están obsoletos } catch (Exception) { } #pragma warning restore 414 } else { nBuilder.SetStyle(estilo); nBuilder.SetLargeIcon(GetImageBitmapFromUrl(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits/" + playeroffline.gettearinstancia().linkeses[playeroffline.gettearinstancia().nombreses.IndexOf(tituloactual)].Split('=')[1])); nBuilder.SetContentTitle(tituloactual); nBuilder.SetContentText(playeroffline.gettearinstancia().linkeses[playeroffline.gettearinstancia().nombreses.IndexOf(tituloactual)]); nBuilder.AddAction(accion5); nBuilder.AddAction(accion3); nBuilder.AddAction(accion1); nBuilder.AddAction(accion2); nBuilder.AddAction(accion4); nBuilder.SetContentIntent(listapending[5]); nBuilder.SetColor(Android.Graphics.Color.ParseColor("#ce2c2b")); // nBuilder.AddAction() } nBuilder.SetOngoing(true); nBuilder.SetSmallIcon(Resource.Drawable.play); Notification notification = nBuilder.Build(); StartForeground(19248736, notification); listapending.Clear(); }
private void CreateBuilder() { var builder = new Notification.Builder(Application.Context, channelId); builder.SetChannelId(channelId); //Configure builder builder.SetContentTitle("track title goes here"); builder.SetContentText("artist goes here"); builder.SetWhen(0); //TODO: set if the notification can be destroyed by swiping //if (infos.dismissable) //{ // builder.setOngoing(false); // Intent dismissIntent = new Intent("music-controls-destroy"); // PendingIntent dismissPendingIntent = PendingIntent.getBroadcast(context, 1, dismissIntent, 0); // builder.setDeleteIntent(dismissPendingIntent); //} //else //{ // builder.setOngoing(true); //} if (AndroidMediaManager.SharedInstance.IsPlaying) { builder.SetOngoing(true); } else { builder.SetOngoing(false); } //If 5.0 >= set the controls to be visible on lockscreen if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop) { builder.SetVisibility(NotificationVisibility.Public); } //Set SmallIcon (Notification Icon in top bar) builder.SetSmallIcon(Android.Resource.Drawable.IcMediaPlay); //TODO: Set LargeIcon // builder.SetLargeIcon(AlbumArt.jpg); //TODO: Open app if tapped //Intent resultIntent = new Intent(context, typeof(Application)); //resultIntent.SetAction(Intent.ActionMain); //resultIntent.AddCategory(Intent.CategoryLauncher); //PendingIntent resultPendingIntent = PendingIntent.GetActivity(context, 0, resultIntent, 0); //builder.SetContentIntent(resultPendingIntent); //Controls var controlsCount = 0; /* Previous */ controlsCount++; builder.AddAction(previousAction); /* Play/Pause */ if (AndroidMediaManager.SharedInstance.IsPlaying) { controlsCount++; builder.AddAction(pauseAction); } else { controlsCount++; builder.AddAction(playAction); } /* Next */ controlsCount++; builder.AddAction(nextAction); /* Close */ //controlsCount++; //builder.AddAction(destroyAction); //If 5.0 >= use MediaStyle if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop) { int[] args = new int[controlsCount]; for (int i = 0; i < controlsCount; ++i) { args[i] = i; } var style = new Notification.MediaStyle(); style.SetShowActionsInCompactView(args); builder.SetStyle(style); } this.notificationBuilder = builder; }
public void mostrarnotificacion() { var listapending = listapendingintents(); RemoteViews contentView = new RemoteViews(PackageName, Resource.Layout.layoutminiplayeronline); if (linkactual.Trim().Length > 1) { try { contentView.SetImageViewBitmap(Resource.Id.imageView1, ImageHelper.GetRoundedShape(GetImageBitmapFromUrl(linkactual))); contentView.SetImageViewBitmap(Resource.Id.fondo1, ImageHelper.CreateBlurredImageFromUrl(this, 20, linkactual)); } catch (Exception) { } } contentView.SetOnClickPendingIntent(Resource.Id.imageView1, listapending[5]); contentView.SetTextViewText(Resource.Id.textView1, tituloactual); contentView.SetOnClickPendingIntent(Resource.Id.imageView2, listapending[0]); contentView.SetOnClickPendingIntent(Resource.Id.imageView4, listapending[1]); contentView.SetOnClickPendingIntent(Resource.Id.imageView3, listapending[2]); contentView.SetOnClickPendingIntent(Resource.Id.imageView6, listapending[3]); contentView.SetOnClickPendingIntent(Resource.Id.imageView5, listapending[4]); /* * * 1-playpause * 2-siguiente * 3-anterior * 4-adelantar * 5-atrazar * */ Notification.Action accion1 = new Notification.Action(Resource.Drawable.playpause, "Playpause", listapending[0]); Notification.Action accion2 = new Notification.Action(Resource.Drawable.skipnext, "Siguiente", listapending[1]); Notification.Action accion3 = new Notification.Action(Resource.Drawable.skipprevious, "Anterior", listapending[2]); Notification.Action accion4 = new Notification.Action(Resource.Drawable.skipforward, "adelantar", listapending[3]); Notification.Action accion5 = new Notification.Action(Resource.Drawable.skipbackward, "atrazar", listapending[4]); #pragma warning disable CS0618 // El tipo o el miembro están obsoletos var nBuilder = new Notification.Builder(this); #pragma warning restore CS0618 // El tipo o el miembro están obsoletos Notification.MediaStyle estilo = new Notification.MediaStyle(); if (Mainmenu.gettearinstancia() != null) { // estilo.SetMediaSession(mainmenu.gettearinstancia().mSession.SessionToken); estilo.SetShowActionsInCompactView(1, 2, 3); } if (Build.VERSION.SdkInt < BuildVersionCodes.Lollipop) { #pragma warning disable 414 try { #pragma warning disable CS0618 // El tipo o el miembro están obsoletos nBuilder.SetContent(contentView); #pragma warning restore CS0618 // El tipo o el miembro están obsoletos } catch (Exception) { } #pragma warning restore 414 } else { nBuilder.SetStyle(estilo); nBuilder.SetLargeIcon(ImageHelper.GetImageBitmapFromUrl(linkactual)); nBuilder.SetContentTitle(tituloactual); nBuilder.SetContentText("Desde: " + Mainmenu.gettearinstancia().devicename); nBuilder.AddAction(accion5); nBuilder.AddAction(accion3); nBuilder.AddAction(accion1); nBuilder.AddAction(accion2); nBuilder.AddAction(accion4); nBuilder.SetContentIntent(listapending[5]); nBuilder.SetColor(Android.Graphics.Color.ParseColor("#ce2c2b")); } nBuilder.SetOngoing(true); nBuilder.SetSmallIcon(Resource.Drawable.play); Notification notification = nBuilder.Build(); StartForeground(19248736, notification); }
private void CreateBuilder(IMediaItem mediaItem) { var builder = new Notification.Builder(Application.Context, channelId); builder.SetChannelId(channelId); //Configure builder builder.SetContentTitle(mediaItem.Title); builder.SetContentText(mediaItem.Artist); builder.SetWhen(0); if (AndroidAudioPlayer.SharedInstance.IsPlaying) { builder.SetOngoing(true); builder.SetSmallIcon(Android.Resource.Drawable.IcMediaPlay); } else { builder.SetOngoing(false); Intent dismissIntent = new Intent(ButtonEvents.AudioControlsDestroy); PendingIntent dismissPendingIntent = PendingIntent.GetBroadcast(Application.Context, 1, dismissIntent, 0); builder.SetDeleteIntent(dismissPendingIntent); builder.SetSmallIcon(Android.Resource.Drawable.IcMediaPause); } //If 5.0 >= set the controls to be visible on lockscreen if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop) { builder.SetVisibility(NotificationVisibility.Public); } if (!string.IsNullOrWhiteSpace(mediaItem.AlbumArtUrl)) { try { var bitmap = new AsyncImageDownloader().Execute(new string[] { mediaItem.AlbumArtUrl }); builder.SetLargeIcon(bitmap.GetResult()); } catch (Java.Lang.Exception exc) { Console.WriteLine($"Unable to find Album Art URL for {mediaItem.AlbumArtUrl}"); Console.WriteLine(exc.ToString()); } } Intent resultIntent = new Intent(Application.Context, typeof(Activity)); resultIntent.SetAction(Intent.ActionMain); resultIntent.AddCategory(Intent.CategoryLauncher); PendingIntent resultPendingIntent = PendingIntent.GetActivity(Application.Context, 0, resultIntent, PendingIntentFlags.UpdateCurrent); builder.SetContentIntent(resultPendingIntent); //Controls var controlsCount = 0; // Previous controlsCount++; builder.AddAction(previousAction); // Play/Pause builder.AddAction(pauseAction); // Next controlsCount++; builder.AddAction(nextAction); // Close //controlsCount++; //builder.AddAction(destroyAction); // If 5.0 >= use MediaStyle if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop) { int[] args = new int[controlsCount]; for (int i = 0; i < controlsCount; ++i) { args[i] = i; } var style = new Notification.MediaStyle(); style.SetShowActionsInCompactView(args); builder.SetStyle(style); } notificationBuilder = builder; }
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); }; }
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 { } }
Notification CreateNotification() { LogHelper.Debug(Tag, "updateNotificationMetadata. mMetadata=" + metadata); if (metadata == null || playbackState == null) { return(null); } var notificationBuilder = new Notification.Builder(service); int playPauseButtonPosition = 0; // If skip to previous action is enabled if ((playbackState.Actions & PlaybackState.ActionSkipToPrevious) != 0) { notificationBuilder.AddAction(Resource.Drawable.ic_skip_previous_white_24dp, service.GetString(Resource.String.label_previous), previousIntent); playPauseButtonPosition = 1; } AddPlayPauseAction(notificationBuilder); // If skip to next action is enabled if ((playbackState.Actions & PlaybackState.ActionSkipToNext) != 0) { notificationBuilder.AddAction(Resource.Drawable.ic_skip_next_white_24dp, service.GetString(Resource.String.label_next), nextIntent); } MediaDescription description = metadata.Description; var fetchArtUrl = string.Empty; Bitmap art = null; if (description.IconUri != null) { String artUrl = description.IconUri.ToString(); art = AlbumArtCache.Instance.GetBigImage(artUrl); if (art == null) { fetchArtUrl = artUrl; art = BitmapFactory.DecodeResource(service.Resources, Resource.Drawable.ic_default_art); } } notificationBuilder .SetStyle(new Notification.MediaStyle() .SetShowActionsInCompactView( new [] { playPauseButtonPosition }) // show only play/pause in compact view .SetMediaSession(sessionToken)) .SetColor(notificationColor) .SetSmallIcon(Resource.Drawable.ic_notification) .SetVisibility(NotificationVisibility.Public) .SetUsesChronometer(true) .SetContentIntent(CreateContentIntent()) .SetContentTitle(description.Title) .SetContentText(description.Subtitle) .SetLargeIcon(art); SetNotificationPlaybackState(notificationBuilder); if (fetchArtUrl != null) { FetchBitmapFromURL(fetchArtUrl, notificationBuilder); } return(notificationBuilder.Build()); }