public override void OnReceive(Context context, Intent intent) { // When the user clicks the notification, SecondActivity will start up. Intent resultIntent = new Intent(context, typeof(MainActivity)); // Construct a back stack for cross-task navigation: Android.App.TaskStackBuilder stackBuilder = Android.App.TaskStackBuilder.Create(context); stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(MainActivity))); stackBuilder.AddNextIntent(resultIntent); // Create the PendingIntent with the back stack: PendingIntent resultPendingIntent = stackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent); // Build the notification: NotificationCompat.Builder builder = new NotificationCompat.Builder(context) .SetAutoCancel(true) // Dismiss from the notif. area when clicked .SetContentIntent(resultPendingIntent) // Start 2nd activity when the intent is clicked. .SetContentTitle("GREATER Campaign") // Set its title .SetNumber(count) // Display the count in the Content Info .SetSmallIcon(Resource.Drawable.icon) // Display this icon .SetContentText(String.Format( "Prayer Guide Reminder. Pray for the GREATER campaign today.", count)); // The message to display. // Finally, publish the notification: NotificationManager notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService); notificationManager.Notify(100, builder.Build()); }
private void SendNotification(string notificationDetails) { Intent notificationIntent = new Intent(ApplicationContext, typeof(MainActivity)); TaskStackBuilder stackBuilder = TaskStackBuilder.Create(this); stackBuilder.AddParentStack(Class.FromType(typeof(MainActivity))); stackBuilder.AddNextIntent(notificationIntent); PendingIntent notificationPendingIntent = stackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent); NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.SetSmallIcon(Resource.Drawable.Icon) .SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.Icon)) .SetColor(Color.Red) .SetContentTitle(notificationDetails) .SetContentText(GetString(Resource.String.geofence_transition_notification_text)) .SetContentIntent(notificationPendingIntent); builder.SetAutoCancel(true); NotificationManager mNotificationManager = (NotificationManager)GetSystemService(Context.NotificationService); mNotificationManager.Notify(0, builder.Build()); }
public void ShowNotification(string title, string content) { var alarmSound = RingtoneManager.GetDefaultUri(RingtoneType.Notification); var intent = new Intent(Application.Context, Class.FromType(typeof(MainActivity))); intent.PutExtra(TitleKey, _title); intent.PutExtra(MessageKey, _content); intent.SetFlags(ActivityFlags.ClearTop); var taskBuilder = TaskStackBuilder.Create(Application.Context); taskBuilder.AddParentStack(Class.FromType(typeof(MainActivity))); taskBuilder.AddNextIntent(intent); var pendingIntent = taskBuilder.GetPendingIntent(DAILY_REMINDER_REQUEST_CODE, PendingIntentFlags.UpdateCurrent); var noticeBuilder = new NotificationCompat.Builder(Application.Context, "default"); var notification = noticeBuilder.SetContentTitle(_title) .SetContentText(_content).SetSound(alarmSound) .SetLargeIcon( BitmapFactory.DecodeResource(Application.Context.Resources, Resource.Drawable.COVCOV)) .SetSmallIcon(Resource.Drawable.abc_ic_star_black_36dp) .SetContentIntent(pendingIntent).Build(); var notificationManager = (NotificationManager)Application.Context.GetSystemService(Context.NotificationService); notificationManager.Notify(DAILY_REMINDER_REQUEST_CODE, notification); }
public static void CreateHistoryReminderNotification(Context context) { var clickIntent = new Intent(context, typeof(ExerciseHistoryActivity)); clickIntent.PutExtra(Constants.ShowMarkedExercisePrompt, false); var stackBuilder = TaskStackBuilder.Create(context); stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(ExerciseHistoryActivity))); stackBuilder.AddNextIntent(clickIntent); var clickPendingIntent = stackBuilder.GetPendingIntent(0, PendingIntentFlags.CancelCurrent); var builder = GetBuilder(context, Constants.TodaysProgressNotificationChannelId) .SetContentTitle(context.Resources.GetString(Resource.String.CheckHistoryNotificationTitle)) .SetContentText(context.Resources.GetString(Resource.String.CheckHistoryNotificationMessage)) .SetDefaults(NotificationCompat.DefaultVibrate) .SetContentIntent(clickPendingIntent) .SetSound(Android.Net.Uri.Parse(PreferenceManager.GetDefaultSharedPreferences(context).GetString(context.Resources.GetString(Resource.String.NotificationSoundKey), RingtoneManager.GetDefaultUri(RingtoneType.Notification).ToString()))) .SetPriority((int)NotificationPriority.High) .SetVisibility(NotificationCompat.VisibilityPublic) .SetCategory("reminder") .SetSmallIcon(Resource.Drawable.Mmm_white_icon) .SetColor(Color.Rgb(215, 78, 10)); var notification = builder.Build(); notification.Flags |= NotificationFlags.AutoCancel; var notificationManager = NotificationManagerCompat.From(context); notificationManager?.Notify(Constants.HistoryReminderNotificationId, notification); }
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { if (intent == null) { return(StartCommandResult.NotSticky); } if (intent.Action == ACTION_STOP) { Stop(); return(StartCommandResult.NotSticky); } else if (intent.Action == ACTION_START) { string host = intent.GetStringExtra(EXTRA_HOST); int port = intent.GetIntExtra(EXTRA_PORT, 1704); EBroadcastMode broadcastMode = (EBroadcastMode)intent.GetIntExtra(EXTRA_BROADCAST_MODE, (int)EBroadcastMode.Media); Intent stopIntent = new Intent(this, typeof(SnapclientService)); stopIntent.SetAction(ACTION_STOP); PendingIntent PiStop = PendingIntent.GetService(this, 0, stopIntent, 0); NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID) .SetSmallIcon(Resource.Drawable.ic_media_play) .SetTicker("Snap.Net.Broadcast started") .SetContentTitle("Snap.Net Broadcast") .SetContentText("Snap.Net.Broadcast is running...") .SetContentInfo(string.Format("{0}:{1}", host, port)) .SetStyle(new NotificationCompat.BigTextStyle().BigText("Snap.Net.Broadcast is running...")) .AddAction(Resource.Drawable.ic_media_stop, "Stop", PiStop); Intent resultIntent = new Intent(this, typeof(MainActivity)); TaskStackBuilder stackBuilder = TaskStackBuilder.Create(this); stackBuilder.AddParentStack(Class.FromType(typeof(MainActivity))); stackBuilder.AddNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.GetPendingIntent( 0, PendingIntentFlags.UpdateCurrent ); builder.SetContentIntent(resultPendingIntent); Notification notification = builder.Build(); StartForeground(NOTIFICATION_CHANNEL, notification); m_MediaProjection = m_MediaProjectionManager.GetMediaProjection((int)Result.Ok, intent.GetParcelableExtra(EXTRA_RESULT_DATA) as Intent); _Start(host, port, broadcastMode); return(StartCommandResult.Sticky); } return(StartCommandResult.NotSticky); }
/// <summary> /// Show a local notification /// </summary> /// <param name="title">Title of the notification</param> /// <param name="body">Body or description of the notification</param> /// <param name="badgecount">Number to be displayed on badge</param> /// <param name="notificationId">Id of the notification</param> /// <param name="messageId">Unique Id of top most message</param> public static void Show(string title, string body, int badgecount = 1, int notificationId = 0, int messageId = 0) { var large = BitmapFactory.DecodeResource(Application.Context.Resources, Resource.Mipmap.ic_launcher); #pragma warning disable 618 var builder = new NotificationCompat.Builder(Application.Context) .SetContentTitle(title) .SetContentText(body) .SetAutoCancel(true) .SetLargeIcon(large) .SetNumber(badgecount) .SetSmallIcon(Resource.Drawable.small_icon); #pragma warning restore 618 // HeadsUp Notification for API 26+ if (Build.VERSION.SdkInt >= BuildVersionCodes.O) { var channel = new NotificationChannel(ChannelId, "Default", NotificationImportance.High); channel.EnableLights(true); channel.LightColor = Color.Pink; channel.EnableVibration(true); channel.SetVibrationPattern(VibrationPattern); channel.SetShowBadge(true); channel.LockscreenVisibility = NotificationVisibility.Public; NotificationManager.CreateNotificationChannel(channel); builder.SetChannelId(ChannelId); } // HeadsUp Notification for API 21+ else if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop) { #pragma warning disable 618 builder.SetPriority((int)NotificationPriority.High); builder.SetVibrate(VibrationPattern); #pragma warning restore 618 } var valuesForActivity = new Bundle(); valuesForActivity.PutInt(MESSAGE_KEY, messageId); // tap action var resultIntent = LauncherActivity; resultIntent.PutExtras(valuesForActivity); resultIntent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop); var stackBuilder = TaskStackBuilder.Create(Application.Context); stackBuilder.AddNextIntent(resultIntent); var resultPendingIntent = stackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent); builder.SetContentIntent(resultPendingIntent); NotificationManager.Notify(notificationId, builder.Build()); }
private static Notification GetNotification(Context ctx, int sessionId, NotificationOption not) { WorkshopDetail session = null; if (not.isWorkshop) { session = Services.Workshop.GetWorkshopFromBookingLocal(sessionId); } else { session = Services.Session.GetSession(sessionId); } var prefix = (not.isWorkshop) ? "" : "Session with "; Notification.Builder mBuilder = new Notification.Builder(ctx) .SetSmallIcon(Resource.Drawable.notificationIcon) .SetContentTitle(prefix + session.Title) .SetContentText(session.Time + " - " + session.DateHumanFriendly) .SetAutoCancel(true) .SetColor(ctx.Resources.GetColor(Resource.Color.primary)) .SetDefaults(NotificationDefaults.All) .SetStyle( new Notification.BigTextStyle().SetSummaryText(session.Title) .BigText(session.Time + " - " + session.DateHumanFriendly + System.Environment.NewLine + session.Room)); try { Looper.Prepare(); } catch (System.Exception ex) { } Intent resultIntent = new Intent(ctx, new ViewSessionActivity().Class); if (not.isWorkshop) { resultIntent = new Intent(ctx, new ViewWorkshopActivity().Class); } resultIntent.PutExtra("Id", sessionId); resultIntent.PutExtra("IsBooking", true); TaskStackBuilder stackBuilder = TaskStackBuilder.Create(ctx); stackBuilder.AddParentStack(new ViewWorkshopActivity().Class); stackBuilder.AddNextIntent(resultIntent); int identifier = (not.isWorkshop) ? 1 : 0; int notificationId = Integer.ParseInt(identifier + sessionId.ToString() + not.mins); PendingIntent resultPendingIntent = stackBuilder.GetPendingIntent(notificationId, PendingIntentFlags.UpdateCurrent); mBuilder.SetContentIntent(resultPendingIntent); return(mBuilder.Build()); }
void CreateNotification(PushNoticationMessage pushMessage) { try { // Get the notifications manager: NotificationManager notificationManager = GetSystemService(Context.NotificationService) as NotificationManager; // Instantiate the notification builder: //TODO: Get the Name of the App from Manifest Notification.Builder builder = new Notification.Builder(this) .SetContentTitle("Quick Task") .SetContentText(pushMessage.Title) .SetAutoCancel(true) .SetSmallIcon(Resource.Drawable.icon) .SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.icon)); builder.SetVisibility(NotificationVisibility.Public); builder.SetPriority((int)NotificationPriority.High); builder.SetCategory(Notification.CategoryMessage); //Setup an intent for the Main Activity: Intent secondIntent = new Intent(this, typeof(MainActivity)); secondIntent.PutExtra("recdMessage", Settings.Current.LastMessage); // Pressing the Back button in SecondActivity exits the app: Android.App.TaskStackBuilder stackBuilder = Android.App.TaskStackBuilder.Create(this); // Add the back stack for the intent: stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(MainActivity))); // Push the intent (that starts SecondActivity) onto the stack. The // pending intent can be used only once (one shot): stackBuilder.AddNextIntent(secondIntent); const int pendingIntentId = 0; PendingIntent pendingIntent = stackBuilder.GetPendingIntent(pendingIntentId, PendingIntentFlags.OneShot); builder.SetContentIntent(pendingIntent); // Build the notification: Notification notification = builder.Build(); notification.Defaults |= NotificationDefaults.Sound; // Notification ID used for all notifications in this app. // Reusing the notification ID prevents the creation of // numerous different notifications as the user experiments // with different notification settings -- each launch reuses // and updates the same notification. const int notificationId = 6; // Launch notification: notificationManager.Notify(notificationId, notification); Log.Info(AppConstants.TAG, "Local Notification Sent"); } catch (Exception ex) { Log.Info(AppConstants.TAG, "Local Notify Failed with " + ex.Message); } }
private static PendingIntent CreatePendingIntent(Context context, Intent intent, bool withParentStack, ActivityFlags?flags) { if (flags.HasValue) { intent.SetFlags(flags.Value); } if (withParentStack) { var stackBuilder = TaskStackBuilder.Create(context); stackBuilder.AddNextIntentWithParentStack(intent); return(stackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent)); } else { return(PendingIntent.GetActivity(context, 0, intent, PendingIntentFlags.UpdateCurrent)); } }
public void Notify(string title, string body, Dictionary <string, string> data) { Intent intent = new Intent(_context, typeof(MainActivity)); PendingIntent pendingIntent = PendingIntent.GetActivity(_context, NotificationId, intent, PendingIntentFlags.OneShot); // Add data to Bundle transfer object Bundle valuesForActivity = new Bundle(); foreach (var item in data) { valuesForActivity.PutString(item.Key, item.Value); } intent.PutExtra(IntentDataKey, valuesForActivity); // When the user clicks the notification, MainActivity will start up and catche Intent Intent resultIntent = new Intent(_context, typeof(MainActivity)); // Pass some values to started Activity: resultIntent.PutExtra(IntentDataKey, valuesForActivity); // Construct a back stack for cross-task navigation: Android.App.TaskStackBuilder stackBuilder = Android.App.TaskStackBuilder.Create(_context); stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(MainActivity))); stackBuilder.AddNextIntent(resultIntent); // Create the PendingIntent with the back stack: PendingIntent resultPendingIntent = stackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent); // Build the notification: NotificationCompat.Builder builder = new NotificationCompat.Builder(_context) .SetAutoCancel(true) // Dismiss from the notif. area when clicked .SetContentIntent(resultPendingIntent) // Start 2nd activity when the intent is clicked. .SetContentTitle(title) // Set its title .SetNumber(4) // Display the count in the Content Info .SetSmallIcon(Resource.Drawable.abc_ic_menu_overflow_material) // Display this icon .SetContentText(body); // The message to display. // Publish the notification: NotificationManager notificationManager = (NotificationManager)_context.GetSystemService(Context.NotificationService); notificationManager.Notify(NotificationId, builder.Build()); }
void CreateNotification(PushNoticationMessage pushedMessage) { // Get the notifications manager: NotificationManager notificationManager = GetSystemService(Context.NotificationService) as NotificationManager; // Instantiate the notification builder: Notification.Builder builder = new Notification.Builder(this) .SetContentTitle("WK Authenticator") .SetContentText(pushedMessage.Title) .SetAutoCancel(true) .SetSmallIcon(Resource.Drawable.icon) .SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.icon)); builder.SetVisibility(NotificationVisibility.Public); builder.SetPriority((int)NotificationPriority.High); builder.SetCategory(Notification.CategoryMessage); //Add Message Information to the Main Activity Intent - This will be shown on Tap Of the Notified Message Intent secondIntent = new Intent(this, typeof(MainActivity)); // Pass the current notification string value to SecondActivity secondIntent.PutExtra("recdMessage", Common.Helpers.Settings.LastMessage); // Pressing the Back button in SecondActivity exits the app: Android.App.TaskStackBuilder stackBuilder = Android.App.TaskStackBuilder.Create(this); // Add the back stack for the intent: stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(MainActivity))); // Push the intent (that starts SecondActivity) onto the stack. The // pending intent can be used only once (one shot): stackBuilder.AddNextIntent(secondIntent); const int pendingIntentId = 0; PendingIntent pendingIntent = stackBuilder.GetPendingIntent(pendingIntentId, PendingIntentFlags.OneShot); builder.SetContentIntent(pendingIntent); // Build the notification: Notification notification = builder.Build(); notification.Defaults |= NotificationDefaults.Sound; // Notification ID used for all notifications in this app. // Reusing the notification ID prevents the creation of numerous different notifications as the user experiments with different notification settings -- each launch reuses // and updates the same notification. const int notificationId = 0; // Launch notification: notificationManager.Notify(notificationId, notification); }
void createNotification(string title, string desc, string confirmToken = null, string alertMessage = null) { //Create notification //Create an intent to show ui Intent uiIntent = new Intent(this, typeof(MainActivity)); if (confirmToken != null && alertMessage != null) { uiIntent.PutExtra("confirmToken", confirmToken.ToString()); uiIntent.PutExtra("alertMessage", alertMessage.ToString()); } Android.App.TaskStackBuilder stackBuilder = Android.App.TaskStackBuilder.Create(this); stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(MainActivity))); stackBuilder.AddNextIntent(uiIntent); const int pendingIntentId = 0; PendingIntent pendingIntent = stackBuilder.GetPendingIntent(pendingIntentId, PendingIntentFlags.OneShot); Notification.Builder builder = new Notification.Builder(this) .SetContentIntent(pendingIntent) .SetContentTitle(title) .SetContentText(desc) .SetSmallIcon(Android.Resource.Drawable.SymActionEmail); // Build the notification: Notification notification = builder.Build(); notification.Flags = NotificationFlags.AutoCancel; // Get the notification manager: NotificationManager notificationManager = GetSystemService(Context.NotificationService) as NotificationManager; // Publish the notification: const int notificationId = 0; notificationManager.Notify(notificationId, notification); }
public Task <List <PermissionState> > RequestPermissions(Context context, string[] permissions, int requestCode) { var tcs = new TaskCompletionSource <List <PermissionState> >(); var rc = new MyResultReceiver(tcs, new Handler(Looper.MainLooper)); var permissionIntent = new Intent(context, typeof(PermissionsRequestActivity)); permissionIntent.PutExtra(PermissionsHelper.KeyResultsReceiver, rc); permissionIntent.PutExtra(PermissionsHelper.KeyPermissions, permissions); permissionIntent.PutExtra(PermissionsHelper.KeyRequestCode, requestCode); CreateChannel(context, "2"); var stackBuilder = TaskStackBuilder.Create(context); stackBuilder.AddNextIntent(permissionIntent); var permPendingIntent = stackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent); var builder = new NotificationCompat.Builder(context, "2"); builder = builder.SetSmallIcon(Resource.Drawable.abc_ic_search_api_material) .SetContentText("this is the test for the permissions notification") .SetContentTitle("this is the title") .SetOngoing(true) .SetAutoCancel(true) .SetWhen(0) .SetContentIntent(permPendingIntent) .SetStyle(null); var notificationManager = NotificationManager.FromContext(context); notificationManager.Notify(requestCode, builder.Build()); return(tcs.Task); }
protected virtual PendingIntent GetLaunchPendingIntent(Notification notification, string actionId = null) { var launchIntent = this .context .AppContext .PackageManager .GetLaunchIntentForPackage(this.context.Package.PackageName) .SetFlags(notification.Android.LaunchActivityFlags.ToNative()); var notificationString = this.serializer.Serialize(notification); launchIntent.PutExtra(AndroidNotificationProcessor.NOTIFICATION_KEY, notificationString); if (!notification.Payload.IsEmpty()) { launchIntent.PutExtra("Payload", notification.Payload); } PendingIntent pendingIntent; if ((notification.Android.LaunchActivityFlags & AndroidActivityFlags.ClearTask) != 0) { pendingIntent = TaskStackBuilder .Create(this.context.AppContext) .AddNextIntent(launchIntent) .GetPendingIntent(notification.Id, PendingIntentFlags.OneShot); } else { pendingIntent = PendingIntent.GetActivity( this.context.AppContext, notification.Id, launchIntent, PendingIntentFlags.OneShot ); } return(pendingIntent); }
//https://stackoverflow.com/questions/45462666/notificationcompat-builder-deprecated-in-android-o public async Task Send(Notification notification) { if (notification.Id == 0) { notification.Id = this.settings.IncrementValue("NotificationId"); } if (notification.ScheduleDate != null) { await this.repository.Set(notification.Id.ToString(), notification); return; } var launchIntent = this .context .AppContext .PackageManager .GetLaunchIntentForPackage(this.context.Package.PackageName) .SetFlags(notification.Android.LaunchActivityFlags.ToNative()); if (!notification.Payload.IsEmpty()) { launchIntent.PutExtra("Payload", notification.Payload); } var pendingIntent = TaskStackBuilder .Create(this.context.AppContext) .AddNextIntent(launchIntent) .GetPendingIntent(notification.Id, PendingIntentFlags.OneShot); //.GetPendingIntent(notification.Id, PendingIntentFlags.OneShot | PendingIntentFlags.CancelCurrent); var smallIconResourceId = this.context.GetResourceIdByName(notification.Android.SmallIconResourceName); var builder = new NotificationCompat.Builder(this.context.AppContext) .SetAutoCancel(true) .SetContentTitle(notification.Title) .SetContentText(notification.Message) .SetSmallIcon(smallIconResourceId) .SetContentIntent(pendingIntent); // TODO //if ((int)Build.VERSION.SdkInt >= 21 && notification.Android.Color != null) // builder.SetColor(notification.Android.Color.Value) if (notification.Android.Priority != null) { builder.SetPriority(notification.Android.Priority.Value); } if (notification.Android.Vibrate) { builder.SetVibrate(new long[] { 500, 500 }); } if (notification.Sound != null) { if (!notification.Sound.Contains("://")) { notification.Sound = $"{ContentResolver.SchemeAndroidResource}://{this.context.Package.PackageName}/raw/{notification.Sound}"; } var uri = Android.Net.Uri.Parse(notification.Sound); builder.SetSound(uri); } if (this.newManager != null) { var channelId = notification.Android.ChannelId; if (this.newManager.GetNotificationChannel(channelId) == null) { var channel = new NotificationChannel( channelId, notification.Android.Channel, notification.Android.NotificationImportance.ToNative() ); var d = notification.Android.ChannelDescription; if (!d.IsEmpty()) { channel.Description = d; } this.newManager.CreateNotificationChannel(channel); } builder.SetChannelId(channelId); this.newManager.Notify(notification.Id, builder.Build()); } else { this.compatManager.Notify(notification.Id, builder.Build()); } }
//https://stackoverflow.com/questions/45462666/notificationcompat-builder-deprecated-in-android-o public async Task Send(Notification notification) { if (notification.Id == 0) { notification.Id = this.settings.IncrementValue("NotificationId"); } if (notification.ScheduleDate != null) { await this.repository.Set(notification.Id.ToString(), notification); return; } var launchIntent = this .context .AppContext .PackageManager .GetLaunchIntentForPackage(this.context.Package.PackageName) .SetFlags(notification.Android.LaunchActivityFlags.ToNative()); var notificationString = this.serializer.Serialize(notification); launchIntent.PutExtra(AndroidNotificationProcessor.NOTIFICATION_KEY, notificationString); if (!notification.Payload.IsEmpty()) { launchIntent.PutExtra("Payload", notification.Payload); } PendingIntent pendingIntent = null; if ((notification.Android.LaunchActivityFlags & AndroidActivityFlags.ClearTask) != 0) { pendingIntent = TaskStackBuilder .Create(this.context.AppContext) .AddNextIntent(launchIntent) .GetPendingIntent(notification.Id, PendingIntentFlags.OneShot); } else { pendingIntent = PendingIntent.GetActivity( this.context.AppContext, notification.Id, launchIntent, PendingIntentFlags.OneShot ); } var smallIconResourceId = this.context.GetResourceIdByName(notification.Android.SmallIconResourceName); if (smallIconResourceId <= 0) { throw new ArgumentException($"No ResourceId found for '{notification.Android.SmallIconResourceName}' - You can set this per notification using notification.Android.SmallIconResourceName or globally using Shiny.Android.AndroidOptions.SmallIconResourceName"); } var builder = new NotificationCompat.Builder(this.context.AppContext) .SetContentTitle(notification.Title) .SetContentText(notification.Message) .SetSmallIcon(smallIconResourceId) .SetContentIntent(pendingIntent); //if ((int)Build.VERSION.SdkInt >= 21 && notification.Android.Color != null) // builder.SetColor(notification.Android.Color.Value) builder.SetAutoCancel(notification.Android.AutoCancel); builder.SetOngoing(notification.Android.OnGoing); if (notification.Android.Priority != null) { builder.SetPriority(notification.Android.Priority.Value); } if (notification.Android.Vibrate) { builder.SetVibrate(new long[] { 500, 500 }); } if (Notification.CustomSoundFilePath.IsEmpty()) { builder.SetSound(Android.Provider.Settings.System.DefaultNotificationUri); } else { var uri = Android.Net.Uri.Parse(Notification.CustomSoundFilePath); builder.SetSound(uri); } if (this.newManager != null) { var channelId = notification.Android.ChannelId; if (this.newManager.GetNotificationChannel(channelId) == null) { var channel = new NotificationChannel( channelId, notification.Android.Channel, notification.Android.NotificationImportance.ToNative() ); var d = notification.Android.ChannelDescription; if (!d.IsEmpty()) { channel.Description = d; } this.newManager.CreateNotificationChannel(channel); } builder.SetChannelId(channelId); this.newManager.Notify(notification.Id, builder.Build()); } else { this.compatManager.Notify(notification.Id, builder.Build()); } await this.services.SafeResolveAndExecute <INotificationDelegate>(x => x.OnReceived(notification)); }
//reads msgs from api every 3 sec private void getMsgs() { var thread = new Thread(async () => { MyMessage[] msgs; Notification.Builder builder = new Notification.Builder(this) .SetAutoCancel(true) .SetSmallIcon(Resource.Drawable.notif) .SetDefaults(NotificationDefaults.Sound); var nMgr = (NotificationManager)GetSystemService(NotificationService); Notification notification = new Notification(Resource.Drawable.notif, "message notification"); Intent intent = new Intent(this, typeof(ChatActivity)); PendingIntent pendingIntent; ViewModel myViewModel = ViewModel.myViewModelInstance; while (true) { string result = await ApiRequests.getMessages(MapActivity.client); msgs = JsonConvert.DeserializeObject<MyMessage[]>(result); if (notifCounter == 0) { for (int i = msgs.Length-1; i >=0; --i) { MyMessage msg = msgs[i]; if (!myViewModel.msgContainer.ContainsKey(msg.message_id)) { myViewModel.msgContainer.Add(msg.message_id, msg); myViewModel.msgsContainer.Add(msg); } } notifCounter++; } else { for (int i = msgs.Length-1; i >= 0; --i) { MyMessage msg = msgs[i]; if (!myViewModel.msgContainer.ContainsKey(msg.message_id)) { myViewModel.msgContainer.Add(msg.message_id, msg); myViewModel.msgsContainer.Add(msg); if (msg.msg_type.Equals("from")) { intent.PutExtra("email", msg.email); intent.PutExtra("firstName", msg.first_name); intent.PutExtra("lastName", msg.last_name); stackBuilder = Android.App.TaskStackBuilder.Create(this); stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(MapActivity))); stackBuilder.AddNextIntent(intent); pendingIntent = PendingIntent.GetActivity(this, notifCounter++, intent, PendingIntentFlags.OneShot); builder.SetContentIntent(pendingIntent); builder.SetContentTitle(msg.first_name + " " + msg.last_name); builder.SetContentText(msg.message); nMgr.Notify(notifCounter++, builder.Build()); BroadcastStarted(msg); } } } } Thread.Sleep(3000); } }); thread.Start(); }
//https://stackoverflow.com/questions/45462666/notificationcompat-builder-deprecated-in-android-o public async Task Send(Notification notification) { if (notification.Id == 0) { notification.Id = this.settings.IncrementValue("NotificationId"); } if (notification.ScheduleDate != null) { await this.repository.Set(notification.Id.ToString(), notification); return; } var launchIntent = this .context .AppContext .PackageManager .GetLaunchIntentForPackage(this.context.Package.PackageName) .SetFlags(notification.Android.LaunchActivityFlags.ToNative()); var notificationString = this.serializer.Serialize(notification); launchIntent.PutExtra(AndroidNotificationProcessor.NOTIFICATION_KEY, notificationString); if (!notification.Payload.IsEmpty()) { launchIntent.PutExtra("Payload", notification.Payload); } var pendingIntent = TaskStackBuilder .Create(this.context.AppContext) .AddNextIntent(launchIntent) .GetPendingIntent(notification.Id, PendingIntentFlags.OneShot); //.GetPendingIntent(notification.Id, PendingIntentFlags.OneShot | PendingIntentFlags.CancelCurrent); var smallIconResourceId = this.context.GetResourceIdByName(notification.Android.SmallIconResourceName); if (smallIconResourceId <= 0) { throw new ArgumentException($"No ResourceId found for '{notification.Android.SmallIconResourceName}' - You can set this per notification using notification.Android.SmallIconResourceName or globally using Shiny.Android.AndroidOptions.SmallIconResourceName"); } var builder = new NotificationCompat.Builder(this.context.AppContext) .SetContentTitle(notification.Title) .SetContentText(notification.Message) .SetSmallIcon(smallIconResourceId) .SetContentIntent(pendingIntent); // TODO //if ((int)Build.VERSION.SdkInt >= 21 && notification.Android.Color != null) // builder.SetColor(notification.Android.Color.Value) builder.SetAutoCancel(notification.Android.AutoCancel); builder.SetOngoing(notification.Android.OnGoing); if (notification.Android.Priority != null) { builder.SetPriority(notification.Android.Priority.Value); } if (notification.Android.Vibrate) { builder.SetVibrate(new long[] { 500, 500 }); } if (notification.Sound != null) { if (!notification.Sound.Contains("://")) { notification.Sound = $"{ContentResolver.SchemeAndroidResource}://{this.context.Package.PackageName}/raw/{notification.Sound}"; } var uri = Android.Net.Uri.Parse(notification.Sound); builder.SetSound(uri); } if (this.newManager != null) { var channelId = notification.Android.ChannelId; if (this.newManager.GetNotificationChannel(channelId) == null) { var channel = new NotificationChannel( channelId, notification.Android.Channel, notification.Android.NotificationImportance.ToNative() ); var d = notification.Android.ChannelDescription; if (!d.IsEmpty()) { channel.Description = d; } this.newManager.CreateNotificationChannel(channel); } builder.SetChannelId(channelId); this.newManager.Notify(notification.Id, builder.Build()); } else { this.compatManager.Notify(notification.Id, builder.Build()); } try { await ShinyHost .Resolve <INotificationDelegate>()? .OnReceived(notification); } catch (Exception ex) { Log.Write(ex); } }
private async Task <Intent> GetContentIntentAsync(NotificationsHelperBase notificationHelper, TaskStackBuilder taskStackBuilder) { bool loginExpired = !(await new LoginService().GetLoginValidityAsync()); ISalesAppSession session = Resolver.Instance.Get <ISalesAppSession>(); if (loginExpired || session == null || session.UserId == default(Guid)) { return(new Intent(AppContext, typeof(LoginActivityView))); } else { Logger.Debug("Session id is " + session.UserId); DestinationInformation destinationInformation = notificationHelper.GetDestinationInformation(); taskStackBuilder.AddParentStack(Class.FromType(destinationInformation.ActivityType)); taskStackBuilder.AddNextIntent(destinationInformation.ContentIntent); return(destinationInformation.ContentIntent); } }
public override void OnReceive(Context context, Intent intent) { Task.Run ( async() => { try { // Wakelocker.Acquire(AppContext, WakelockTag); // await new LocalOtaService().CacheAsync(); Logger.Debug("Notification OnReceive called"); int savedNotificationType = intent.GetIntExtra(NotificationType, 0); if (savedNotificationType == 0) { Logger.Error("Unknown notification type"); return; } Logger.Debug("Notification type is " + savedNotificationType); NotificationTypes notificationType = (NotificationTypes)savedNotificationType; Logger.Debug("Showing notification of type " + notificationType.ToString()); if (notificationType == default(NotificationTypes)) { return; } Logger.Debug("Booting up the core notification service"); NotificationsCoreService notificationsCoreService = new NotificationsCoreService(); Logger.Debug("Requesting core notification service for overdue notifications"); List <string> overdueNotifications = await notificationsCoreService.GetOverdueNotificationsEntityIdsAsync(notificationType); Logger.Debug("Establishing the notification helper to use"); NotificationsHelperBase notificationHelper = GetHelper(notificationType); Logger.Debug("Asking notification helper to filter out notifications that aren't needed"); await notificationHelper.SetOverdueNotificationsAsync(overdueNotifications); if (overdueNotifications == null) { overdueNotifications = new List <string>(); } if (overdueNotifications.Count == 0) { Logger.Debug("Turns out there are no notifications to show"); return; } string message = notificationHelper.GetMessage(); PendingIntent contentIntent = PendingIntent.GetActivity(context, default(int), intent, PendingIntentFlags.CancelCurrent); var notificationManager = NotificationManagerCompat.From(context); var style = new NotificationCompat.BigTextStyle(); style.BigText(message); var builder = new NotificationCompat.Builder(AppContext) .SetContentTitle(notificationHelper.GetTitle()) .SetContentText(notificationHelper.GetMessage()) .SetAutoCancel(notificationHelper.AutoCancel) .SetContentIntent(contentIntent) .SetSmallIcon(Resource.Drawable.Icon22x22) .SetStyle(style) .SetDefaults((int)notificationHelper.SoundAndOrVibrationAndOrLights) .SetWhen(JavaSystem.CurrentTimeMillis()); TaskStackBuilder taskStackBuilder = TaskStackBuilder.Create(AppContext); Intent destIntent = await GetContentIntentAsync(notificationHelper, taskStackBuilder); if (destIntent != null) { PendingIntent pendingIntent = taskStackBuilder.GetPendingIntent(0, PendingIntentFlags.OneShot); //PendingIntent.GetActivity(AppContext, 0, destIntent, PendingIntentFlags.OneShot); builder.SetContentIntent(pendingIntent); } var notification = builder.Build(); notificationManager.Notify((int)notificationType, notification); } catch (Exception ex) { Logger.Error(ex); throw; } finally { Wakelocker.Release(); } } ); }
public static void CreateExerciseNotification(Data data, Context context, ExerciseBlock nextExercise) { if (nextExercise == null) { return; } var completedIntent = new Intent(context, typeof(CompleteExerciseBroadcastReceiver)); completedIntent.PutExtra(Constants.ExerciseName, nextExercise.CombinedName); completedIntent.PutExtra(Constants.ExerciseQuantity, nextExercise.Quantity); var completedPendingIntent = PendingIntent.GetBroadcast(context, DateTime.Now.Millisecond, completedIntent, PendingIntentFlags.OneShot); var nextIntent = new Intent(context, typeof(ChangeExerciseBroadcastReceiver)); nextIntent.PutExtra(Constants.ExerciseName, nextExercise.CombinedName); nextIntent.PutExtra(Constants.ExerciseQuantity, nextExercise.Quantity); var nextPendingIntent = PendingIntent.GetBroadcast(context, DateTime.Now.Millisecond, nextIntent, PendingIntentFlags.CancelCurrent); var clickIntent = new Intent(context, typeof(ExerciseHistoryActivity)); clickIntent.PutExtra(Constants.ShowMarkedExercisePrompt, true); clickIntent.PutExtra(Constants.ExerciseId, nextExercise.Id); var stackBuilder = TaskStackBuilder.Create(context); stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(ExerciseHistoryActivity))); stackBuilder.AddNextIntent(clickIntent); var clickPendingIntent = stackBuilder.GetPendingIntent(0, PendingIntentFlags.CancelCurrent); data.MarkExerciseNotified(nextExercise.CombinedName, nextExercise.Quantity); var timeToMoveMessage = string.Format(context.Resources.GetString(Resource.String.TimeToMoveMessage), nextExercise.Quantity, nextExercise.CombinedName); var builder = GetBuilder(context, Constants.ExerciseNotificationChannelId) .SetContentTitle(context.Resources.GetString(Resource.String.TimeToMoveTitle)) .SetContentText(timeToMoveMessage) .SetDefaults(NotificationCompat.DefaultVibrate) .SetContentIntent(clickPendingIntent) .SetSound(Android.Net.Uri.Parse(PreferenceManager.GetDefaultSharedPreferences(context).GetString(context.Resources.GetString(Resource.String.NotificationSoundKey), RingtoneManager.GetDefaultUri(RingtoneType.Notification).ToString()))); var changeExerciseButtonText = context.Resources.GetString(Resource.String.ChangeExerciseButtonText); var completedButtonText = context.Resources.GetString(Resource.String.CompletedButtonText); builder .SetPriority((int)NotificationPriority.High) .SetVisibility(NotificationCompat.VisibilityPublic) .SetCategory("reminder") .SetSmallIcon(Resource.Drawable.Mmm_white_icon) .SetColor(Color.Rgb(215, 78, 10)) .AddAction(new NotificationCompat.Action(Resource.Drawable.ic_shuffle_black_24dp, changeExerciseButtonText, nextPendingIntent)) .AddAction(new NotificationCompat.Action(Resource.Drawable.ic_done_black_24dp, completedButtonText, completedPendingIntent)); var notification = builder.Build(); notification.Flags |= NotificationFlags.AutoCancel; var notificationManager = NotificationManagerCompat.From(context); notificationManager?.Notify(Constants.ExerciseNotificationId, notification); }