public virtual void OnPrepareSupportNavigateUpTaskStack(TaskStackBuilder builder) { }
/*public new bool OnMenuItemSelected(int featureId, IMenuItem item) { const int DisplayHomeAsUp = 4; if (base.OnMenuItemSelected(featureId, item)) { return true; } var supportActionBar = this.AppCompatDelegate.SupportActionBar; if (item.ItemId == Resource.Id.home || supportActionBar == null) { return false; } if ((supportActionBar.DisplayOptions & DisplayHomeAsUp) != 0) { return this.OnSupportNavigateUp(); } return false; }*/ public override void OnPrepareSupportNavigateUpTaskStack(TaskStackBuilder builder) { }
public virtual void OnCreateSupportNavigateUpTaskStack(TaskStackBuilder builder) { builder.AddParentStack(this); }
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.ps4_tools) .SetLargeIcon(BitmapFactory.DecodeResource(context.Resources, Resource.Drawable.ps4_tools)); 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 override void OnCreateSupportNavigateUpTaskStack(TaskStackBuilder builder) { builder.AddParentStack(this); }
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); }; }
/* * private void HttpReq_mRequestCompleted(object sender, RequestEventArgs e) * { * Toast.MakeText(this, e.Response, ToastLength.Long).Show(); * } */ private void MainAppActivity_Poll(object sender, EventArgs e) { string result; using (WebClient client = new WebClient()) { Uri uri = new Uri("http://35.165.103.236:80/geteta"); NameValueCollection parameters = new NameValueCollection(); parameters.Add("useremail", mCredentials.Get("email")); byte[] response = client.UploadValues(uri, parameters); result = System.Text.Encoding.UTF8.GetString(response); if (result.Substring(0, 1) == "0") { RunOnUiThread(() => { txtInfo.Text = result.Substring(1); }); } else if (result.Substring(0, 1) == "*") { //VERZOEK AFGEHANDELD requestPending = false;//stop polling for info //threadRunning = false; RunOnUiThread(() => { Toast.MakeText(this, result, ToastLength.Long).Show(); }); } else { if (Convert.ToInt16(result) != ETA) { sentNotification = false; ETA = Convert.ToInt16(result); //set ETA RunOnUiThread(() => { txtInfo.Text = result.ToString(); }); currentETA = ETA; } else if (currentETA > 60) { currentETA--; RunOnUiThread(() => { txtInfo.Text = (currentETA / 60).ToString() + "min"; }); } else { RunOnUiThread(() => { txtInfo.Text = "The deliverer will arrive soon"; }); if (!sentNotification) { sentNotification = true; Intent resultIntent = new Intent(this, typeof(MainAppActivity)); // Construct a back stack for cross-task navigation: TaskStackBuilder stackBuilder = TaskStackBuilder.Create(this); stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(MainAppActivity))); stackBuilder.AddNextIntent(resultIntent); // Create the PendingIntent with the back stack: PendingIntent resultPendingIntent = stackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent); Android.Net.Uri alarmSound = RingtoneManager.GetDefaultUri(RingtoneType.Notification); Notification.Builder builder = new Notification.Builder(this) .SetContentTitle("Uber Ijsco") .SetContentText("Your Deliverer will arrive shortly") .SetAutoCancel(true) // Dismiss from the notif. area when clicked .SetContentIntent(resultPendingIntent) // Start 2nd activity when the intent is clicked. .SetSmallIcon(Android.Resource.Drawable.IcDialogAlert) .SetSound(alarmSound) .SetVibrate(new long[] { 500, 500, 500, 500, 500 }) .SetPriority(10); // Build the notification: Notification driverCloseNotificiation = builder.Build(); // Get the notification manager: NotificationManager notificationManager = GetSystemService(Context.NotificationService) as NotificationManager; // Publish the notification: const int notificationId = 0; notificationManager.Notify(notificationId, driverCloseNotificiation); } } } } }
protected override void OnCreate(Bundle bundle) { TabLayoutResource = Resource.Layout.tabs; ToolbarResource = Resource.Layout.toolbar; base.OnCreate(bundle); notificationManager = GetSystemService(Context.NotificationService) as NotificationManager; global::Xamarin.Forms.Forms.Init(this, bundle); var fooApp = new App(new AndroidInitializer()); #region 檢查是否是由通知開啟 App,並且依據通知,切換到適當頁面 //自訂通知被點擊後的動作 //當通知出現在通知欄之後,在習慣的趨使下,有很大的機率會被使用者點擊。 //所以應該要實作出通知被點擊後的動作,好比開啟哪個Activity之類的。 //通知被點擊後的動作可以使用PendingIntent來實作,PendingIntent並不是一個Intent,它是一個Intent的容器, // 可以傳入context物件,並以這個context的身份來做一些事情,例如開啟Activity、開啟Service,或是發送Broadcast。 // 如果要使通知可以在被點擊之後做點什麼事,可以使用Notification.Builder的setContentIntent方法來替通知加入PendingIntent fooLocalNotificationPayload = null; if (Intent.Extras != null) { if (Intent.Extras.ContainsKey("NotificationObject")) { string fooNotificationObject = Intent.Extras.GetString("NotificationObject", ""); fooLocalNotificationPayload = JsonConvert.DeserializeObject <LocalNotificationPayload>(fooNotificationObject); } } #endregion XFLocalNotificationDroid.App.fooLocalNotificationPayload = fooLocalNotificationPayload; LoadApplication(new App(new AndroidInitializer())); #region 訂閱要發送本地通知的事件 // 取得 Xamarin.Forms 中的 Prism 注入物件管理容器 IUnityContainer myContainer = (App.Current as PrismApplication).Container; var fooEvent = myContainer.Resolve <IEventAggregator>().GetEvent <LocalNotificationEvent>().Subscribe(x => { #region 建立本地訊息通知物件 Notification.Builder builder = new Notification.Builder(this) .SetContentTitle(x.ContentTitle) .SetContentText(x.ContentText) .SetSmallIcon(Resource.Drawable.ic_notification) .SetAutoCancel(true); // 決定是否要顯示大圖示 if (x.LargeIcon) { builder.SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.monkey_icon)); } #region 針對不同通知類型作出設定 switch (x.Style) { case LocalNotificationStyleEnum.Normal: break; case LocalNotificationStyleEnum.BigText: //builder.SetContentText(x.ContentText); var textStyle = new Notification.BigTextStyle(); textStyle.BigText(x.ContentText); textStyle.SetSummaryText(x.SummaryText); builder.SetStyle(textStyle); break; case LocalNotificationStyleEnum.Inbox: var inboxStyle = new Notification.InboxStyle(); foreach (var item in x.InboxStyleList) { inboxStyle.AddLine(item); } inboxStyle.SetSummaryText(x.SummaryText); builder.SetStyle(inboxStyle); break; case LocalNotificationStyleEnum.Image: var picStyle = new Notification.BigPictureStyle(); picStyle.BigPicture(BitmapFactory.DecodeResource(Resources, Resource.Drawable.x_bldg)); picStyle.SetSummaryText(x.SummaryText); builder.SetStyle(picStyle); break; default: break; } #endregion #region 設定 visibility switch (x.Visibility) { case LocalNotificationVisibilityEnum.Public: builder.SetVisibility(NotificationVisibility.Public); break; case LocalNotificationVisibilityEnum.Private: builder.SetVisibility(NotificationVisibility.Private); break; case LocalNotificationVisibilityEnum.Secret: builder.SetVisibility(NotificationVisibility.Secret); break; default: break; } #endregion #region 設定 priority switch (x.Priority) { case LocalNotificationPriorityEnum.Default: builder.SetPriority((int)NotificationPriority.Default); break; case LocalNotificationPriorityEnum.High: builder.SetPriority((int)NotificationPriority.High); break; case LocalNotificationPriorityEnum.Low: builder.SetPriority((int)NotificationPriority.Low); break; case LocalNotificationPriorityEnum.Maximum: builder.SetPriority((int)NotificationPriority.Max); break; case LocalNotificationPriorityEnum.Minimum: builder.SetPriority((int)NotificationPriority.Min); break; default: break; } #endregion #region 設定 category switch (x.Category) { case LocalNotificationCategoryEnum.Call: builder.SetCategory(LocalNotificationCategoryEnum.Call.ToString()); break; case LocalNotificationCategoryEnum.Message: builder.SetCategory(LocalNotificationCategoryEnum.Message.ToString()); break; case LocalNotificationCategoryEnum.Alarm: builder.SetCategory(LocalNotificationCategoryEnum.Alarm.ToString()); break; case LocalNotificationCategoryEnum.Email: builder.SetCategory(LocalNotificationCategoryEnum.Email.ToString()); break; case LocalNotificationCategoryEnum.Event: builder.SetCategory(LocalNotificationCategoryEnum.Event.ToString()); break; case LocalNotificationCategoryEnum.Promo: builder.SetCategory(LocalNotificationCategoryEnum.Promo.ToString()); break; case LocalNotificationCategoryEnum.Progress: builder.SetCategory(LocalNotificationCategoryEnum.Progress.ToString()); break; case LocalNotificationCategoryEnum.Social: builder.SetCategory(LocalNotificationCategoryEnum.Social.ToString()); break; case LocalNotificationCategoryEnum.Error: builder.SetCategory(LocalNotificationCategoryEnum.Error.ToString()); break; case LocalNotificationCategoryEnum.Transport: builder.SetCategory(LocalNotificationCategoryEnum.Transport.ToString()); break; case LocalNotificationCategoryEnum.System: builder.SetCategory(LocalNotificationCategoryEnum.System.ToString()); break; case LocalNotificationCategoryEnum.Service: builder.SetCategory(LocalNotificationCategoryEnum.Service.ToString()); break; case LocalNotificationCategoryEnum.Recommendation: builder.SetCategory(LocalNotificationCategoryEnum.Recommendation.ToString()); break; case LocalNotificationCategoryEnum.Status: builder.SetCategory(LocalNotificationCategoryEnum.Status.ToString()); break; default: break; } #endregion #region 準備設定當使用者點選通知之後要做的動作 // Setup an intent for SecondActivity: Intent secondIntent = new Intent(this, typeof(MainActivity)); // 設定當使用點選這個通知之後,要傳遞過去的資料 secondIntent.PutExtra("NotificationObject", JsonConvert.SerializeObject(x)); // 若在首頁且使用者按下回上頁實體按鈕,則會離開這個 App TaskStackBuilder stackBuilder = TaskStackBuilder.Create(this); stackBuilder.AddNextIntent(secondIntent); PendingIntent pendingIntent = stackBuilder.GetPendingIntent(pendingIntentId++, PendingIntentFlags.OneShot); // Uncomment this code to setup an intent so that notifications return to this app: // Intent intent = new Intent (this, typeof(MainActivity)); // const int pendingIntentId = 0; // pendingIntent = PendingIntent.GetActivity (this, pendingIntentId, intent, PendingIntentFlags.OneShot); // builder.SetContentText("Hello World! This is my first action notification!"); // Launch SecondActivity when the users taps the notification: builder.SetContentIntent(pendingIntent); // 產生一個 notification 物件 Notification notification = builder.Build(); #region 決定是否要發出聲音 if (x.Sound) { notification.Defaults |= NotificationDefaults.Sound; } #endregion #region 決定是否要有震動 if (x.Vibrate) { notification.Defaults |= NotificationDefaults.Vibrate; } #endregion // 顯示本地通知: notificationManager.Notify(notificationId++, notification); // 解開底下程式碼註解,將會於五秒鐘之後,才會發生本地通知 // Thread.Sleep(5000); // builder.SetContentTitle("Updated Notification"); // builder.SetContentText("Changed to this message after five seconds."); // notification = builder.Build(); // notificationManager.Notify(notificationId, notification); #endregion #endregion }); #endregion }
public override Task Send(Notification notification) { if (notification.Id == null) { Services.Repository.CurrentScheduleId++; notification.Id = Services.Repository.CurrentScheduleId; } //if (string.IsNullOrEmpty(notification.IconName)) //{ // notification.IconName = Notification.DefaultIcon; //} if (notification.IsScheduled) { var triggerMs = this.GetEpochMills(notification.SendTime); var pending = notification.ToPendingIntent(notification.Id.Value); this.alarmManager.Set( AlarmType.RtcWakeup, Convert.ToInt64(triggerMs), pending ); Services.Repository.Insert(notification); } else { var iconResourceId = Application.Context.Resources.GetIdentifier(notification.IconName, "drawable", Application.Context.PackageName); var launchIntent = Application.Context.PackageManager.GetLaunchIntentForPackage(Application.Context.PackageName); launchIntent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask); foreach (var pair in notification.Metadata) { launchIntent.PutExtra(pair.Key, pair.Value); } var builder = new NotificationCompat.Builder(Application.Context) .SetAutoCancel(true) .SetContentTitle(notification.Title) .SetContentText(notification.Message) .SetSmallIcon(iconResourceId) .SetContentIntent(TaskStackBuilder .Create(Application.Context) .AddNextIntent(launchIntent) .GetPendingIntent(notification.Id.Value, PendingIntentFlags.OneShot) ); if (notification.Vibrate) { builder.SetVibrate(new long[] { 500, 500 }); } // Sound if (string.IsNullOrEmpty(notification.Sound)) { notification.Sound = Notification.DefaultSound; } if (notification.Sound != null) { if (!notification.Sound.Contains("://")) { notification.Sound = $"{ContentResolver.SchemeAndroidResource}://{Application.Context.PackageName}/raw/{notification.Sound}"; } var soundUri = DroidURI.Parse(notification.Sound); builder.SetSound(soundUri); } else if (Notification.SystemSoundFallback) { // Fallback to the system default notification sound // if both Sound prop and Default prop are null var soundUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification); builder.SetSound(soundUri); } var not = builder.Build(); NotificationManagerCompat .From(Application.Context) .Notify(notification.Id.Value, not); } return(Task.CompletedTask); }
/*public new bool OnMenuItemSelected(int featureId, IMenuItem item) * { * const int DisplayHomeAsUp = 4; * * if (base.OnMenuItemSelected(featureId, item)) * { * return true; * } * * var supportActionBar = this.AppCompatDelegate.SupportActionBar; * * if (item.ItemId == Resource.Id.home || supportActionBar == null) * { * return false; * } * * if ((supportActionBar.DisplayOptions & DisplayHomeAsUp) != 0) * { * return this.OnSupportNavigateUp(); * } * * return false; * }*/ public override void OnPrepareSupportNavigateUpTaskStack(TaskStackBuilder builder) { }
public void notificationThreadFunctie() { int aantalNieuweKlanten = 0; int vorigAantalNieuweKlanten = 0; List <Klant> serverKlanten = new List <Klant>(); List <Klant> geweigerdeKlanten = new List <Klant>(); KlantDataService dataService = new KlantDataService(); //while (threadRunning == true) //zorg voor een eeuwige lus while (true) //zorg voor een eeuwige lus { if (threadRunning == true) { Thread.Sleep(7000); using (WebClient wc = new WebClient()) { var json = wc.DownloadString("http://35.165.103.236:80/unhandledclients"); serverKlanten = JsonConvert.DeserializeObject <List <Klant> >(json); } //serverKlanten = dataService.GeefAlleKlantenFromServer(); geweigerdeKlanten = dataService.getGewijgerdeKlanten(); aantalNieuweKlanten = serverKlanten.Count; //maximum aantal nieuwe klanten (gelijk aan server klanten) if (geweigerdeKlanten[0].Username != "XXXXGEENKLANTENXXXX") //wanneer er nog geen gewijgerde klanten zijn { for (int i = 0; i < serverKlanten.Count; i++) { for (int j = 0; j < geweigerdeKlanten.Count; j++) { if (serverKlanten == geweigerdeKlanten) //als bepaalde klant op de server == aan de reeds geweigerde klant { aantalNieuweKlanten--; //wordt maximum aantal klanten verminderd met 1 } } } } if (aantalNieuweKlanten != 0 && aantalNieuweKlanten != vorigAantalNieuweKlanten) { vorigAantalNieuweKlanten++; //voor het maken van de klik event // When the user clicks the notification, SecondActivity will start up. Intent resultIntent = new Intent(this, typeof(AccepteerActivity)); // Construct a back stack for cross-task navigation: TaskStackBuilder stackBuilder = TaskStackBuilder.Create(this); stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(AccepteerActivity))); stackBuilder.AddNextIntent(resultIntent); // Create the PendingIntent with the back stack: PendingIntent resultPendingIntent = stackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent); Android.Net.Uri alarmSound = Android.Media.RingtoneManager.GetDefaultUri(Android.Media.RingtoneType.Notification); Notification.Builder builder = new Notification.Builder(this) .SetContentTitle("Nieuwe klanten") .SetContentText("Er zijn " + aantalNieuweKlanten + " nieuwe klanten") .SetAutoCancel(true) // Dismiss from the notif. area when clicked .SetContentIntent(resultPendingIntent) // Start 2nd activity when the intent is clicked. .SetSmallIcon(Android.Resource.Drawable.IcDialogAlert) .SetSound(alarmSound) .SetVibrate(new long[] { 500, 500, 500, 500, 500 }) .SetPriority(10); // Build the notification: Notification nieuweKlantNotification = builder.Build(); // Get the notification manager: NotificationManager notificationManager = GetSystemService(Context.NotificationService) as NotificationManager; // Publish the notification: const int notificationId = 0; notificationManager.Notify(notificationId, nieuweKlantNotification); } } } }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { var prefs = GetSharedPreferences("KiedyTest", FileCreationMode.Private); int req_timeout = prefs.GetInt("connection_timeout", 0); string heartbeat_url = "http://dziennik.zs1debica.pl/kiedytest/android/request_handler/heartbeat.php?app_type=uczen&app_version=1.0"; ////// HEARTBEAT EXCUTER /////// _timer = new Timer(o => { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(heartbeat_url); request.Timeout = req_timeout; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK) { Stream receiveStream = response.GetResponseStream(); StreamReader readStream = null; if (response.CharacterSet == null) { readStream = new StreamReader(receiveStream); } else { readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet)); } data = readStream.ReadToEnd(); response.Close(); readStream.Close(); } network_ok = true; } catch (WebException ex) { network_ok = false; } }, null, 0, 60000); /// Koniec timera /////////////////////////////// string content, content2; string user_name = prefs.GetString("login", null); string user_password = prefs.GetString("password", null); string urlAddress = "http://dziennik.zs1debica.pl/kiedytest/android/request_handler/get_planned_test_notification.php?user_name=" + user_name + "&user_password="******"notify_enabled", null); if (notify_enabled == "yes") { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress); request.Timeout = req_timeout; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK) { Stream receiveStream = response.GetResponseStream(); StreamReader readStream = null; if (response.CharacterSet == null) { readStream = new StreamReader(receiveStream); } else { readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet)); } data = readStream.ReadToEnd(); response.Close(); readStream.Close(); } network_ok = true; } catch (WebException ex) { network_ok = false; } content2 = data; ////////////////////////// if (network_ok) { content = data; try { content = content.Replace("\x00", ""); // // AWESOME !!!!! // in my case I want to see it, otherwise just replace with "" MemoryStream memStream = new MemoryStream(); byte[] data2 = System.Text.Encoding.UTF8.GetBytes(content); memStream.Write(data2, 0, data2.Length); memStream.Position = 0; XmlDocument doc = new XmlDocument(); doc.LoadXml(content); string noti_type; int noti_type_INT; noti_type_INT = 0; string noti_test_id; noti_test_id = null; int noti_test_id_INT; noti_test_id_INT = 0; string noti_pending; noti_pending = null; int noti_pending_INT; noti_pending_INT = 0; noti_type = "kot"; int c = 0; string noti_body; noti_body = null; string vibration, sound; vibration = null; sound = null; int vibration_INT, sound_INT; vibration_INT = 0; sound_INT = 0; foreach (XmlElement x in doc.SelectNodes("notification/notification_data/notification_type")) { c++; noti_type = x.InnerXml; Console.Write(x.InnerXml); } ////// Checking if any notifications available //////// foreach (XmlElement x in doc.SelectNodes("notification/notification_data/pending_notifications_count")) { c++; noti_pending = x.InnerXml; Console.Write(x.InnerXml); } ////// Checking test id //////// foreach (XmlElement x in doc.SelectNodes("notification/notification_data/test_id")) { c++; noti_test_id = x.InnerXml; Console.Write(x.InnerXml); } ////// Checking notification text //////// foreach (XmlElement x in doc.SelectNodes("notification/notification_data/notification_body")) { c++; noti_body = x.InnerXml; Console.Write(x.InnerXml); } ////// Checking if user enabled sound //////// foreach (XmlElement x in doc.SelectNodes("notification/notification_data/sound")) { c++; sound = x.InnerXml; Console.Write(x.InnerXml); } ////// Checking if user enabled vibration //////// foreach (XmlElement x in doc.SelectNodes("notification/notification_data/vibration")) { c++; vibration = x.InnerXml; Console.Write(x.InnerXml); } /// Converting variables////////////////// int.TryParse(noti_pending, out noti_pending_INT); int.TryParse(noti_type, out noti_type_INT); //int.TryParse(noti_test_id, out noti_test_id_INT); int.TryParse(sound, out sound_INT); int.TryParse(vibration, out vibration_INT); /////////////////////////////////////// if (noti_pending_INT > 0) { /// DATA FOR OTHER ACTIVITY/// int test_id; int randomcount; // float count2; // count2 = 08.06f; test_id = noti_test_id_INT; Bundle valuesForActivity = new Bundle(); valuesForActivity.PutString("test_id", noti_test_id); if (noti_type_INT == 1) { valuesForActivity.PutString("display_type", "onlyone"); } if (noti_type_INT == 2) { if (noti_pending_INT > 1) { valuesForActivity.PutString("display_type", "all"); } else { valuesForActivity.PutString("display_type", "onlyone"); } } // When the user clicks the notification, SecondActivity will start up. Intent resultIntent = new Intent(this, typeof(Activity1)); // Pass some values to SecondActivity: resultIntent.PutExtras(valuesForActivity); // Construct a back stack for cross-task navigation: TaskStackBuilder stackBuilder = TaskStackBuilder.Create(this); stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(Activity1))); stackBuilder.AddNextIntent(resultIntent); // Create the PendingIntent with the back stack: PendingIntent resultPendingIntent = stackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent); ///////////////////////////////////////////////////////////////////////////////// if (noti_type_INT == 1) { // Build the notification: Notification.Builder builder = new Notification.Builder(this) .SetAutoCancel(true) // Dismiss from the notif. area when clicked .SetContentIntent(resultPendingIntent) // Start 2nd activity when the intent is clicked. .SetContentTitle("Nowy zapowiedziany test!") // Set its title // .SetNumber(count) // Display the count in the Content Info .SetSmallIcon(App7.Resource.Drawable.Icon) // Display this icon .SetContentText(String.Format( noti_body)); // The message to display. // Finally, publish the notification: NotificationManager notificationManager = (NotificationManager)GetSystemService(Context.NotificationService); Random rand1 = new Random(); randomcount = rand1.Next(); if (sound_INT == 1 && vibration_INT == 1) { builder.SetDefaults(NotificationDefaults.Sound | NotificationDefaults.Vibrate); } else if (sound_INT == 1) { builder.SetDefaults(NotificationDefaults.Sound); } else if (vibration_INT == 1) { builder.SetDefaults(NotificationDefaults.Vibrate); } // builder.SetDefaults( NotificationDefaults.Vibrate); notificationManager.Notify(randomcount, builder.Build()); } if (noti_type_INT == 2) { string new_test_parsed_title; if (noti_pending_INT > 1) { new_test_parsed_title = "Nowe zapowiedziane testy!"; } else { new_test_parsed_title = "Nowy zapowiedziany test!"; } // Build the notification: Notification.Builder builder = new Notification.Builder(this) .SetAutoCancel(true) // Dismiss from the notif. area when clicked .SetContentIntent(resultPendingIntent) // Start 2nd activity when the intent is clicked. .SetContentTitle(new_test_parsed_title) // Set its title // .SetNumber(count) // Display the count in the Content Info .SetSmallIcon(App7.Resource.Drawable.Icon) // Display this icon .SetContentText(String.Format( noti_body)); // The message to display. // Instantiate the Big Text style: Notification.BigTextStyle textStyle = new Notification.BigTextStyle(); // Fill it with text: string longTextMessage = noti_body; // longTextMessage += " / Just like me. "; //... textStyle.BigText(longTextMessage); // Set the summary text: if (noti_pending_INT == 1) { tests_grammar = " nowy zapowiedziany test"; } if (noti_pending_INT > 1 && noti_pending_INT < 5) { tests_grammar = " nowe zapowiedziane testy"; } if (noti_pending_INT > 5) { tests_grammar = " nowych zapowiedzianych testów"; } textStyle.SetSummaryText(noti_pending + tests_grammar); // Plug this style into the builder: builder.SetStyle(textStyle); // Finally, publish the notification: NotificationManager notificationManager = (NotificationManager)GetSystemService(Context.NotificationService); Random rand1 = new Random(); randomcount = rand1.Next(); if (sound_INT == 1 && vibration_INT == 1) { builder.SetDefaults(NotificationDefaults.Sound | NotificationDefaults.Vibrate); } else if (sound_INT == 1) { builder.SetDefaults(NotificationDefaults.Sound); } else if (vibration_INT == 1) { builder.SetDefaults(NotificationDefaults.Vibrate); } // builder.SetDefaults( NotificationDefaults.Vibrate); notificationManager.Notify(randomcount, builder.Build()); } } } catch (Exception ex) { // just suppress any error logging exceptions } } /// IF network ok END } }, null, 0, TimerWait); /// Koniec timera return(START_STICKY); }
public override Task Send(Notification notification) { if (notification.Id == null) { Services.Repository.CurrentScheduleId++; notification.Id = Services.Repository.CurrentScheduleId; } if (notification.IsScheduled) { var triggerMs = this.GetEpochMills(notification.SendTime); var pending = notification.ToPendingIntent(notification.Id.Value); this.alarmManager.Set( AlarmType.RtcWakeup, Convert.ToInt64(triggerMs), pending ); Services.Repository.Insert(notification); } else { var launchIntent = Application.Context.PackageManager.GetLaunchIntentForPackage(Application.Context.PackageName); launchIntent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask); foreach (var pair in notification.Metadata) { launchIntent.PutExtra(pair.Key, pair.Value); } var builder = new Android.App.Notification.Builder(Application.Context) .SetAutoCancel(true) .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification)) .SetContentTitle(notification.Title) .SetContentText(notification.Message) .SetSmallIcon(AppIconResourceId) .SetPriority(priority.HasValue ? priority.Value : NotificationCompat.PriorityMax) .SetContentIntent(TaskStackBuilder .Create(Application.Context) .AddNextIntent(launchIntent) .GetPendingIntent(notification.Id.Value, PendingIntentFlags.OneShot) ); if (notification.Vibrate) { builder.SetVibrate(new long[] { 500, 500 }); } if (notification.Sound != null) { if (!notification.Sound.Contains("://")) { notification.Sound = $"{ContentResolver.SchemeAndroidResource}://{Application.Context.PackageName}/raw/{notification.Sound}"; } var uri = Android.Net.Uri.Parse(notification.Sound); builder.SetSound(uri); } var not = builder.Build(); NotificationManagerCompat .From(Application.Context) .Notify(notification.Id.Value, not); } return(Task.CompletedTask); }