void createNotification(string title, string desc) { //Create notification var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager; //Create an intent to show UI var uiIntent = new Intent(this, typeof(MainActivity)); //Create the notification var notification = new Notification(Android.Resource.Drawable.SymActionEmail, title); //Auto-cancel will remove the notification once the user touches it notification.Flags = NotificationFlags.AutoCancel; //Set the notification info //we use the pending intent, passing our ui intent over, which will get called //when the notification is tapped. notification.SetLatestEventInfo(this, title, desc, PendingIntent.GetActivity(this, 0, uiIntent, 0)); //Show the notification notificationManager.Notify(1, notification); dialogNotify(title, desc); }
private void SetAlarm(int RequestCode, double Seconds) { var calendar = Calendar.Instance; calendar.Add(CalendarField.Second, Convert.ToInt32(Seconds)); var am = GetSystemService(Context.AlarmService) as AlarmManager; var intent = new Intent(this, typeof(MyAlarmReciver)); intent.PutExtra("ALARM_TYPE", RequestCode); intent.AddFlags(ActivityFlags.IncludeStoppedPackages); intent.AddFlags(ActivityFlags.ReceiverForeground); var pi = PendingIntent.GetBroadcast(this, RequestCode, intent, PendingIntentFlags.UpdateCurrent); if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.M) { am.SetExactAndAllowWhileIdle(AlarmType.RtcWakeup, calendar.TimeInMillis, pi); } else { am.SetExact(AlarmType.RtcWakeup, calendar.TimeInMillis, pi); } }
void OneShotClick(object sender, EventArgs e) { // When the alarm goes off, we want to broadcast an Intent to our // BroadcastReceiver. Here we make an Intent with an explicit class // name to have our own receiver (which has been published in // AndroidManifest.xml) instantiated and called, and then create an // IntentSender to have the intent executed as a broadcast. var intent = new Intent(this, typeof(OneShotAlarm)); var source = PendingIntent.GetBroadcast(this, 0, intent, 0); // Schedule the alarm for 30 seconds from now! var am = (AlarmManager)GetSystemService(AlarmService); am.Set(AlarmType.ElapsedRealtime, SystemClock.ElapsedRealtime() + 30 * 1000, source); // Tell the user about what we did. if (repeating != null) { repeating.Cancel(); } repeating = Toast.MakeText(this, Resource.String.one_shot_scheduled, ToastLength.Long); repeating.Show(); }
void SendNotification(string messageBody, IDictionary <string, string> data) { var intent = new Intent(this, typeof(AlarmsHistoryActivity)); intent.AddFlags(ActivityFlags.ClearTop); foreach (var key in data.Keys) { intent.PutExtra(key, data[key]); } var pendingIntent = PendingIntent.GetActivity(this, NotificationActivity.NOTIFICATION_ID, intent, PendingIntentFlags.OneShot); var notificationBuilder = new NotificationCompat.Builder(this, NotificationActivity.CHANNEL_ID) .SetSmallIcon(Resource.Drawable.notification) .SetContentTitle("FCM Message") .SetContentText(messageBody) .SetAutoCancel(true) .SetContentIntent(pendingIntent); var notificationManager = NotificationManagerCompat.From(this); notificationManager.Notify(NotificationActivity.NOTIFICATION_ID, notificationBuilder.Build()); }
public void SendNotification(string title, string message, DateTime?notifyTime = null) { if (!channelInitialized) { CreateNotificationChannel(); } if (notifyTime != null) { Intent intent = new Intent(AndroidApp.Context, typeof(AlarmHandler)); intent.PutExtra(TitleKey, title); intent.PutExtra(MessageKey, message); PendingIntent pendingIntent = PendingIntent.GetBroadcast(AndroidApp.Context, pendingIntentId++, intent, PendingIntentFlags.CancelCurrent); long triggerTime = GetNotifyTime(notifyTime.Value); AlarmManager alarmManager = AndroidApp.Context.GetSystemService(Context.AlarmService) as AlarmManager; alarmManager.Set(AlarmType.RtcWakeup, triggerTime, pendingIntent); } else { Show(title, message); } }
void SendNotification(string messageBody, IDictionary <string, string> data) { var intent = new Intent(this, typeof(LoginActivity)); intent.AddFlags(ActivityFlags.ClearTop); foreach (string key in data.Keys) { intent.PutExtra(key, data[key]); } var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot); var notificationBuilder = new Notification.Builder(this) .SetSmallIcon(Resource.Drawable.isotipo) .SetContentTitle("Host state") .SetContentText(messageBody) .SetAutoCancel(true) .SetContentIntent(pendingIntent); var notificationManager = NotificationManager.FromContext(this); notificationManager.Notify(0, notificationBuilder.Build()); }
/** * Starts the specified purchase intent with the specified activity. * * @param activity * @param purchaseIntent * purchase intent. * @param intent */ public static void startPurchaseIntent(Activity activity, PendingIntent purchaseIntent, Intent intent) { if (Compatibility.isStartIntentSenderSupported()) { // This is on Android 2.0 and beyond. The in-app buy page activity // must be on the activity stack of the application. Compatibility.startIntentSender(activity, purchaseIntent.IntentSender, intent); } else { // This is on Android version 1.6. The in-app buy page activity must // be on its own separate activity stack instead of on the activity // stack of the application. try { purchaseIntent.Send(activity, 0 /* code */, intent); } catch (Android.App.PendingIntent.CanceledException e) { Log.Error(LOG_TAG, "Error starting purchase intent", e); } } }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.main_activity); mAddGeofencesButton = FindViewById <Button> (Resource.Id.add_geofences_button); mRemoveGeofencesButton = FindViewById <Button> (Resource.Id.remove_geofences_button); mAddGeofencesButton.Click += AddGeofencesButtonHandler; mRemoveGeofencesButton.Click += RemoveGeofencesButtonHandler; mGeofenceList = new List <IGeofence> (); mGeofencePendingIntent = null; mSharedPreferences = GetSharedPreferences(Constants.SHARED_PREFERENCES_NAME, FileCreationMode.Private); mGeofencesAdded = mSharedPreferences.GetBoolean(Constants.GEOFENCES_ADDED_KEY, false); SetButtonsEnabledState(); PopulateGeofenceList(); BuildGoogleApiClient(); }
public NFCMessage OnResume() { if (!Init) { return(NFCMessage.NFC_NOT_INITIALIZED); } else if (NfcAdapter == null) { return(NFCMessage.NFC_NOT_AVAILABLE); } else if (!NfcAdapter.IsEnabled) { return(NFCMessage.NFC_DISABLED); } else { var filters = Actions.Select(s => new IntentFilter(s)).ToArray(); var intent = new Intent(_act, _act.GetType()).AddFlags(ActivityFlags.SingleTop); var pendingIntent = PendingIntent.GetActivity(_act, 0, intent, 0); NfcAdapter.EnableForegroundDispatch(_act, pendingIntent, filters, null); return(NFCMessage.NFC_NO_ERROR); } }
private void Switch_Toggled(object sender, ToggledEventArgs e) { if (e.Value == true) { Switch sw = (Switch)sender; var Clocks = (Clocks)sw.BindingContext; Intent intent = new Intent(Android.App.Application.Context, typeof(AlarmRecevier)); PendingIntent intent1 = PendingIntent.GetBroadcast(Android.App.Application.Context, Cl.Count, intent, PendingIntentFlags.UpdateCurrent); Clocks.SetAlarm(intent1); var p = (StackLayout)sw.Parent; var c = (Label)p.Children[0]; c.TextColor = Color.Black; } else { Switch sw = (Switch)sender; var Clocks = (Clocks)sw.BindingContext; Clocks.OffAlarm(); var p = (StackLayout)sw.Parent; var c = (Label)p.Children[0]; c.TextColor = Color.Gray; } }
private void Notification(Intent activity, string text, string group, int intent_id, int notification_id) { //creates a Pending intent with the activity sent to the notification PendingIntent pendingIntent = PendingIntent.GetActivity(this, intent_id, activity, PendingIntentFlags.OneShot); //creates a notification based on the intent and message of the notification Notification.Builder builder = new Notification.Builder(this); builder.SetContentIntent(pendingIntent); builder.SetContentTitle("Who's Home?"); builder.SetContentText(text + group); builder.SetSmallIcon(Resource.Drawable.ic_action_content_save); // Build the notification Notification notification = builder.Build(); // Get the notification manager: NotificationManager notificationManager = GetSystemService(Context.NotificationService) as NotificationManager; // Publish the notification: notificationManager.Notify(notification_id, notification); }
/// <summary> /// The schedule alarm. /// </summary> /// <param name="wakeUp"> /// The wake up. /// </param> private void ScheduleAlarm(int wakeUp) { var alarms = this.GetSystemService(AlarmService).JavaCast <AlarmManager>(); if (alarms == null) { Log.Debug(Tag, "LVLDL couldn't get alarm manager"); return; } Calendar cal = Calendar.Instance; cal.Add(CalendarField.Second, wakeUp); Log.Debug(Tag, "LVLDL scheduling retry in {0} seconds ({1})", wakeUp, cal.Time.ToLocaleString()); var intent = new Intent(DownloaderServiceActions.ActionRetry); intent.PutExtra(DownloaderServiceExtras.PendingIntent, this.pPendingIntent); intent.SetClassName(this.PackageName, this.AlarmReceiverClassName); this.alarmIntent = PendingIntent.GetBroadcast(this, 0, intent, PendingIntentFlags.OneShot); alarms.Set(AlarmType.RtcWakeup, cal.TimeInMillis, this.alarmIntent); }
void SendNotification(string title, string message) { var activityIntent = new Intent(this, typeof(MainActivity)); activityIntent.SetFlags(ActivityFlags.SingleTop | ActivityFlags.ClearTop); var pendingIntent = PendingIntent.GetActivity(this, 0, activityIntent, PendingIntentFlags.UpdateCurrent); var defaultSoundUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification); var n = new NotificationCompat.Builder(this) .SetSmallIcon(Resource.Drawable.notification_template_icon_bg) .SetLights(global::Android.Graphics.Color.Green, 300, 1000) .SetContentIntent(pendingIntent) .SetContentTitle(title) .SetTicker(message) .SetContentText(message) .SetAutoCancel(true) .SetSound(defaultSoundUri) .SetVibrate(new long[] { 200, 200, 100 }); var nm = NotificationManager.FromContext(Forms.Context); nm.Notify(0, n.Build()); }
internal void ScheduleTrade() { var context = Application.Context; var manager = AlarmManager.FromContext(context); using (var intent = new Intent(context, this.GetType())) using (var alarmIntent = PendingIntent.GetService(context, 0, intent, PendingIntentFlags.UpdateCurrent)) { if (this.Settings.NextTradeTime > 0) { var currentTime = Java.Lang.JavaSystem.CurrentTimeMillis(); Info("Current UNIX time is {0}.", currentTime); var nextTradeTime = Math.Max(GetEarliestTradeTime(), this.Settings.NextTradeTime); manager.Set(AlarmType.RtcWakeup, nextTradeTime, alarmIntent); Info("Set alarm time to {0}.", nextTradeTime); } else { manager.Cancel(alarmIntent); Info("Cancelled alarm."); } } }
void createNotification(string title, string desc) { //Create notification var notificationManager = GetSystemService(NotificationService) as NotificationManager; App.IsNewsPage = true; //Create an intent to show ui var uiIntent = new Intent(this, typeof(SplashScreen)); //Create the notification var notification = new Notification(Resource.Drawable.azurelogo_30, title); //Auto cancel will remove the notification once the user touches it notification.Flags = NotificationFlags.AutoCancel; //Set the notification info //we use the pending intent, passing our ui intent over which will get called //when the notification is tapped. notification.SetLatestEventInfo(this, title, desc, PendingIntent.GetActivity(this, 0, uiIntent, 0)); //Show the notification notificationManager.Notify(1, notification); }
public async Task StartReadingAsync() { if (!await IsReaderAvailableAsync()) { throw new InvalidOperationException("NFC reader not available"); } if (!await IsReaderEnabledAsync()) { throw new InvalidOperationException("NFC reader is not enabled"); } var act = CurrentActivity; var tagDetected = new IntentFilter(NfcAdapter.ActionNdefDiscovered); tagDetected.AddDataType("*/*"); var filters = new[] { tagDetected }; var intent = new Intent(act, act.GetType()).AddFlags(ActivityFlags.SingleTop); var pendingIntent = PendingIntent.GetActivity(act, 0, intent, 0); _nfcAdapter.EnableReaderMode(act, this, NfcReaderFlags.NfcA | NfcReaderFlags.NoPlatformSounds, null); }
public static MainActivity Main; //We need reference to MainActivity located in MainActivity.cs file public static void ShowNotification(bool isRepeating, int interval) { if (Main == null) { Console.WriteLine("Can't show notifications because of null in MainActivity."); return; } Context context = Main as Context; AlarmManager manager = (AlarmManager)Main.GetSystemService(Context.AlarmService); Intent myIntent = new Intent(context, typeof(AlarmNotificationReceiver)); PendingIntent pendingIntent = PendingIntent.GetBroadcast(context, 0, myIntent, 0); long now = SystemClock.ElapsedRealtime(); if (!isRepeating) { manager.Set(AlarmType.ElapsedRealtimeWakeup, now + interval, pendingIntent); } else { manager.SetRepeating(AlarmType.ElapsedRealtimeWakeup, now + interval, interval, pendingIntent); } }
public void SetListeners(RemoteViews view) { //listener 1 ////Intent volume = new Intent(parent, NotificationReturnSlot.class); ////volume.putExtra("DO", "volume"); ////PendingIntent btn1 = PendingIntent.getActivity(parent, 0, volume, 0); //// view.setOnClickPendingIntent(R.id.btn1, btn1); //listener 2 Intent stop = new Intent(parent, typeof(NotificationReturnSlot)); stop.PutExtra("DO", "stopNotification"); PendingIntent btn1 = PendingIntent.GetActivity(parent, 0, stop, 0); view.SetOnClickPendingIntent(Resource.Id.btn1, btn1); Intent frederik = new Intent(parent, typeof(NotificationReturnSlot)); stop.PutExtra("DO", "frederik"); PendingIntent btn2 = PendingIntent.GetActivity(parent, 1, stop, 0); view.SetOnClickPendingIntent(Resource.Id.btn2, btn2); }
public void AddNotification(Note note) { if (IsNotificationAllowed) { DateTime time = DateTime.ParseExact(note.TimeOfNote, @"dd-MM-yyyy HH\:mm", System.Globalization.CultureInfo.InvariantCulture); string nameRoom = note.RoomName.Replace("A", "Aula ") .Replace("BW", " £azienka damska").Replace("BM", " £azienka mêska") .Replace("SDD", "Schody w dó³ od zielonej").Replace("SDU", "Schody w górê od zielonej") .Replace("SUD", "Schody w dó³ od ¿ó³tej").Replace("SUU", "Schody w górê od ¿ó³tej"); Intent intent = new Intent(context, typeof(MainActivity)); intent.PutExtra("RoomId", note.RoomID); const int pendingIntentId = 0; PendingIntent pendingIntent = PendingIntent.GetActivity(context, pendingIntentId, intent, PendingIntentFlags.OneShot); Notification.Builder builder = new Notification.Builder(context) .SetAutoCancel(true) .SetContentIntent(pendingIntent) .SetContentTitle($"{note.TextOfNote} za { timerNotifications } min w {(nameRoom.Contains("Aula") ? "" : "sali")} { nameRoom }") .SetContentText("Chcesz zobaczyæ mapê?") .SetSmallIcon(Resource.Drawable.Icon) .SetWhen((DateTime.Now - time).Ticks); Notification notification = builder.Build(); NotificationManager notificationManager = context.GetSystemService(Context.NotificationService) as NotificationManager; const int notificationId = 0; notificationManager.Notify(notificationId, notification); } else { AlertDialog.Builder alert = new AlertDialog.Builder(context); alert.SetMessage("Powiadomienia w aplikacji s¹ wy³¹czone, aby je w³¹czyæ proszê przejœæ do ustawieñ."); Dialog dialog = alert.Create(); dialog.Show(); } }
void SendNotification(Context context, string title, string message) { Random rm = new Random(); int NotificationId = rm.Next(9999); var channelId = "MyApp Channel"; var mainIntent = new Intent(context, typeof(MainActivity)); mainIntent.PutExtra("NotificationId", NotificationId); mainIntent.AddFlags(ActivityFlags.ClearTop); var pendingIntent = PendingIntent.GetActivity(context, NotificationId, mainIntent, PendingIntentFlags.UpdateCurrent); var style = new NotificationCompat.BigTextStyle(); style.BigText(title); var defaultSoundUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification); var notificationBuilder = new NotificationCompat.Builder(context, channelId) .SetContentTitle("MyApp - " + title) .SetContentText(message) .SetAutoCancel(true) .SetSound(defaultSoundUri) .SetContentIntent(pendingIntent) .SetSmallIcon(Resource.Drawable.icon); var notificationManager = NotificationManager.FromContext(context); if (global::Android.OS.Build.VERSION.SdkInt >= global::Android.OS.BuildVersionCodes.O) { NotificationChannel mChannel = new NotificationChannel(channelId, "MyApp", NotificationImportance.High); notificationManager.CreateNotificationChannel(mChannel); notificationBuilder.SetChannelId(channelId); } notificationManager.Notify(NotificationId, notificationBuilder.Build()); }
internal static void StartNotification( Context context, MediaMetadata mediaMetadata, AndroidMedia.Session.MediaSession mediaSession, Object largeIcon, bool isPlaying) { var pendingIntent = PendingIntent.GetActivity( context, 0, new Intent(context, typeof(MainActivity)), PendingIntentFlags.UpdateCurrent); MediaMetadata currentTrack = mediaMetadata; MediaStyle style = new MediaStyle(); style.SetMediaSession(mediaSession.SessionToken); var builder = new Notification.Builder(context, CHANNEL_ID) .SetStyle(style) .SetContentTitle(currentTrack.GetString(MediaMetadata.MetadataKeyTitle)) .SetContentText(currentTrack.GetString(MediaMetadata.MetadataKeyArtist)) .SetSubText(currentTrack.GetString(MediaMetadata.MetadataKeyAlbum)) .SetSmallIcon(Resource.Drawable.player_play) .SetLargeIcon(largeIcon as Bitmap) .SetContentIntent(pendingIntent) .SetShowWhen(false) .SetOngoing(isPlaying) .SetVisibility(NotificationVisibility.Public); builder.AddAction(NotificationHelper.GenerateActionCompat(context, Drawable.IcMediaPrevious, "Previous", MediaPlayerService.ActionPrevious)); AddPlayPauseActionCompat(builder, context, isPlaying); builder.AddAction(NotificationHelper.GenerateActionCompat(context, Drawable.IcMediaNext, "Next", MediaPlayerService.ActionNext)); style.SetShowActionsInCompactView(0, 1, 2); NotificationManagerCompat.From(context).Notify(NotificationId, builder.Build()); }
public override void OnMessageReceived(RemoteMessage message) { string messageTitle = message.GetNotification().Title; string messageBody = message.GetNotification().Body; string base64Question = null; if (message?.Data?.Count > 0) { message.Data.TryGetValue("question", out base64Question); } // (Re)open the app via the main intent var intent = new Intent(this, typeof(MainActivity)); intent.AddFlags(ActivityFlags.ClearTop); intent.PutExtra("question", base64Question); PendingIntent pendingIntent = PendingIntent.GetActivity(this, MainActivity.NotificationId, intent, PendingIntentFlags.OneShot); // Build and fire local notification var notificationBuilder = new NotificationCompat.Builder(this, PlatformNotificationService.NotificationChannelId) .SetSmallIcon(Resource.Mipmap.solene_flag) .SetContentTitle(messageTitle) .SetContentText(messageBody) .SetAutoCancel(true) .SetContentIntent(pendingIntent); var notificationManager = NotificationManagerCompat.From(this); notificationManager.Notify(MainActivity.NotificationId, notificationBuilder.Build()); // TODO: In addition to firing a toast notification, we should also just update // the underlying profile up in the cross-platform app. }
public static void ShowNotification() { try { var resultIntent = new Intent(Android.App.Application.Context, typeof(MainActivity)); resultIntent.AddFlags(ActivityFlags.NewTask); var resultPendingIntent = PendingIntent.GetActivity(Android.App.Application.Context, 0 /* Request code */, resultIntent, PendingIntentFlags.UpdateCurrent); var builder = new NotificationCompat.Builder(Android.App.Application.Context) .SetSmallIcon(Resource.Drawable.LogoSmall) .SetContentTitle("Budget.ly") .SetContentText("Zapisz wydatki!") .SetAutoCancel(true) .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification)) .SetContentIntent(resultPendingIntent); var notificationManager = Android.App.Application.Context.GetSystemService(Context.NotificationService) as NotificationManager; if (Build.VERSION.SdkInt >= BuildVersionCodes.O) { if (notificationManager.GetNotificationChannel(CHANNEL_ID) == null) { CreateNotificationChannel(); } builder.SetChannelId(CHANNEL_ID); } var notification = builder.Build(); notificationManager.Notify(_notificationId++, builder.Build()); } catch (Exception exc) { var msg = exc.Message; } }
void CreateNotification(string title, string desc, string parameters = null) { Intent startupIntent = new Intent(this, typeof(MainActivity)); startupIntent.PutExtra("param", parameters.ToString()); TaskStackBuilder stackBuilder = TaskStackBuilder.Create(this); stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(MainActivity))); stackBuilder.AddNextIntent(startupIntent); 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(Resource.Drawable.icon); // 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); }
private NotificationCompat.Builder GetNotificationBuilder(string intentText, int descResId, int drawableResId, string entryName, Bitmap entryIcon) { String desc = _ctx.GetString(descResId); String title = _ctx.GetString(Resource.String.app_name); if (!String.IsNullOrEmpty(entryName)) { title += " (" + entryName + ")"; } PendingIntent pending; if (intentText == null) { pending = PendingIntent.GetActivity(_ctx.ApplicationContext, 0, new Intent(), 0); } else { pending = GetPendingIntent(intentText, descResId); } var builder = new NotificationCompat.Builder(_ctx, App.NotificationChannelIdEntry); builder.SetSmallIcon(drawableResId) .SetContentText(desc) .SetContentTitle(entryName) .SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis()) .SetTicker(entryName + ": " + desc) .SetVisibility((int)Android.App.NotificationVisibility.Secret) .SetContentIntent(pending); if (entryIcon != null) { builder.SetLargeIcon(entryIcon); } return(builder); }
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); }
public static void updateNotification(Context ctx, string title, string content, string extra) { //NOTE ref https://developer.xamarin.com/guides/cross-platform/application_fundamentals/notifications/android/local_notifications_in_android/ var intent = new Intent(ctx, typeof(MainActivity)); intent.PutExtra("msg_from_noti", extra); TaskStackBuilder stackBuilder = TaskStackBuilder.Create(ctx); stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(MainActivity))); stackBuilder.AddNextIntent(intent); const int pendingIntentId = 0; PendingIntent pendingIntent = stackBuilder.GetPendingIntent(pendingIntentId, PendingIntentFlags.OneShot); Notification.Builder builder = new Notification.Builder(ctx) .SetContentIntent(pendingIntent) .SetContentTitle(title) .SetContentText(content) .SetAutoCancel(true) // dismiss the notification from the notification area when the user clicks on it .SetDefaults(NotificationDefaults.Lights | NotificationDefaults.Vibrate) // 如果設定了 NotificationDefaults.Sound, 自訂的音效就會被預設的取代 //.SetSound (RingtoneManager.GetDefaultUri (RingtoneType.Alarm))//.SetSound (alarmSound, 5) // 更多聲音控制去參考 diantou .SetSound(Android.Net.Uri.Parse("android.resource://" + Application.Context.PackageName + "/" + Resource.Raw.SMW_Coin)) //.SetWhen (Java.Lang.JavaSystem.CurrentTimeMillis () + 120000)// 這只是設定通知上顯示的時間, 並非此通知被發出的時間 .SetSmallIcon(Resource.Drawable.Icon); Notification notification = builder.Build(); var notificationManager = ctx.GetSystemService(Context.NotificationService) as NotificationManager; const int notificationId = 0; notificationManager.Notify(notificationId, notification); }
/// <summary> /// Schedule the download of the big picture associated with the content. </summary> /// <param name="context"> any application context. </param> /// <param name="content"> content with big picture notification. </param> public static void downloadBigPicture(Context context, EngagementReachInteractiveContent content) { /* Set up download request */ DownloadManager downloadManager = (DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE); Uri uri = Uri.parse(content.NotificationBigPicture); DownloadManager.Request request = new DownloadManager.Request(uri); request.NotificationVisibility = DownloadManager.Request.VISIBILITY_HIDDEN; request.VisibleInDownloadsUi = false; /* Create intermediate directories */ File dir = context.getExternalFilesDir("engagement"); dir = new File(dir, "big-picture"); dir.mkdirs(); /* Set destination */ long contentId = content.LocalId; request.DestinationUri = Uri.fromFile(new File(dir, contentId.ToString())); /* Submit download */ long id = downloadManager.enqueue(request); content.setDownloadId(context, id); /* Set up timeout on download */ Intent intent = new Intent(EngagementReachAgent.INTENT_ACTION_DOWNLOAD_TIMEOUT); intent.putExtra(EngagementReachAgent.INTENT_EXTRA_CONTENT_ID, contentId); intent.Package = context.PackageName; PendingIntent operation = PendingIntent.getBroadcast(context, (int)contentId, intent, 0); long triggerAtMillis = SystemClock.elapsedRealtime() + DOWNLOAD_TIMEOUT; AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); alarmManager.set(ELAPSED_REALTIME_WAKEUP, triggerAtMillis, operation); }
public void Show(LocalNotification notification) { var context = MainApplication.Context; var builder = new NotificationCompat.Builder(context); builder.SetContentTitle(notification.Title); builder.SetContentText(notification.Body); builder.SetOngoing(notification.Ongoing); builder.SetWhen(notification.Timestamp.GetEpochMillis()); if (notification.ProgressPercentage != null) { builder.SetProgress(100, notification.ProgressPercentage.Value, false); } if (notification.Color != null) { builder.SetColor(notification.Color.Value.ToAndroid().ToArgb()); } if (notification.Icon != null) { builder.SetSmallIcon(context.Resources.GetIdentifier(Path.GetFileNameWithoutExtension(notification.Icon), "drawable", context.PackageName)); } else { builder.SetSmallIcon(Resource.Drawable.alarm63); } if (notification.BroadcastMessage != null) { var intent = new Intent(context, typeof(NotificationActionService)).PutExtra(ExtraNotificationId, notification.Id).PutExtra(ExtraBroadcastMessage, notification.BroadcastMessage); builder.SetContentIntent(PendingIntent.GetService(context, 0, intent, PendingIntentFlags.Immutable)); } var notificationManager = NotificationManagerCompat.From(context); notificationManager.Notify(notification.Id, builder.Build()); }
private bool GetExpansionFiles() { bool result = false; // Build the intent that launches this activity. Intent launchIntent = this.Intent; var intent = new Intent(this, typeof(DownloaderActivity)); intent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTop); intent.SetAction(launchIntent.Action); if (launchIntent.Categories != null) { foreach (string category in launchIntent.Categories) { intent.AddCategory(category); } } // Build PendingIntent used to open this activity when user // taps the notification. PendingIntent pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.UpdateCurrent); // Request to start the download DownloadServiceRequirement startResult = DownloaderService.StartDownloadServiceIfRequired(this, pendingIntent, typeof(SampleDownloaderService)); // The DownloaderService has started downloading the files, // show progress otherwise, the download is not needed so we // fall through to starting the actual app. if (startResult != DownloadServiceRequirement.NoDownloadRequired) { this.downloaderServiceConnection = ClientMarshaller.CreateStub(this, typeof(SampleDownloaderService)); result = true; } return result; }