public override void OnReceive(Context context, Intent intent)
		{
			if (!MainActivity.REPLY_ACTION.Equals(intent.Action))
				return;


			var requestId = intent.GetIntExtra(MainActivity.REQUEST_CODE_KEY, -1);
			if (requestId == -1)
				return;

			var reply = GetMessageText(intent);
			using (var notificationManager = NotificationManagerCompat.From(context))
			{
				// Create new notification to display, or re-build existing conversation to update with new response
				var notificationBuilder = new NotificationCompat.Builder(context);
				notificationBuilder.SetSmallIcon(Resource.Drawable.reply);
				notificationBuilder.SetContentText(Application.Context.GetString(Resource.String.replied));
				var repliedNotification = notificationBuilder.Build();


				// Call notify to stop progress spinner. 
				notificationManager.Notify(requestId, repliedNotification);
			}

			Toast.MakeText(context, $"Message sent: {reply}", ToastLength.Long).Show();
		}
Ejemplo n.º 2
0
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Android.OS.Bundle savedInstanceState)
        {
            var ignored = base.OnCreateView(inflater, container, savedInstanceState);
            var view = inflater.Inflate(Resource.Layout.fragment_profile, null);
            m_ImageLoader = new ImageLoader(Activity);
            view.FindViewById<TextView>(Resource.Id.profile_name).Text = "James Montemagno";
            view.FindViewById<TextView>(Resource.Id.profile_description).Text = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.";
            m_ImageLoader.DisplayImage("https://lh6.googleusercontent.com/-cGOyhvv0Xb0/UQV41NcgFHI/AAAAAAAAKz4/MKYmmtSgajI/w140-h140-p/6b27f0ec682011e2bd9a22000a9f14ba_7.jpg", view.FindViewById<ImageView>(Resource.Id.profile_image), -1);

            view.FindViewById<ImageView>(Resource.Id.profile_image).Click += (sender, args) =>
                {
                    var builder = new NotificationCompat.Builder(Activity)
                    .SetSmallIcon(Resource.Drawable.ic_launcher)
                    .SetContentTitle("Click to go to friend details!")
                    .SetContentText("New Friend!!");
                            
                    var friendActivity = new Intent(Activity, typeof(FriendActivity));

                    PendingIntent pendingIntent = PendingIntent.GetActivity(Activity, 0, friendActivity, 0);
                  

                    builder.SetContentIntent(pendingIntent);
                    builder.SetAutoCancel(true);
                    var notificationManager = 
                        (NotificationManager) Activity.GetSystemService(Context.NotificationService);
                    notificationManager.Notify(0, builder.Build());
                };
            return view;
        }
Ejemplo n.º 3
0
        public override void OnReceive(Context context, Intent intent)
        {
            var id = intent.GetStringExtra("id");
            var message = intent.GetStringExtra("message");
            var title = intent.GetStringExtra("title");

            var notIntent = new Intent(context, typeof(MainActivity));
            notIntent.PutExtra("id", id);
            var contentIntent = PendingIntent.GetActivity(context, 0, notIntent, PendingIntentFlags.CancelCurrent);
            var manager = NotificationManagerCompat.From(context);

            int resourceId = Resource.Drawable.ic_launcher_xx;

            var wearableExtender = new NotificationCompat.WearableExtender()
                .SetBackground(BitmapFactory.DecodeResource(context.Resources, resourceId));

            //Generate a notification with just short text and small icon
            var builder = new NotificationCompat.Builder(context)
                            .SetContentIntent(contentIntent)
                            .SetSmallIcon(Resource.Drawable.ic_launcher_xx)
                            .SetContentTitle(title)
                            .SetContentText(message)
                            .SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis())
                            .SetAutoCancel(true)
                            .Extend(wearableExtender);

            var notification = builder.Build();
            manager.Notify(int.Parse(id), notification);
        }
Ejemplo n.º 4
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

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

            var v = FindViewById<WatchViewStub>(Resource.Id.watch_view_stub);
            v.LayoutInflated += delegate
            {

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

                button.Click += delegate
                {
                    var notification = new NotificationCompat.Builder(this)
                        .SetContentTitle("Button tapped")
                        .SetContentText("Button tapped " + count++ + " times!")
                        .SetSmallIcon(Android.Resource.Drawable.StatNotifyVoicemail)
                        .SetGroup("group_key_demo").Build();

                    var manager = NotificationManagerCompat.From(this);
                    manager.Notify(1, notification);
                    button.Text = "Check Notification!";
                };
            };
        }
Ejemplo n.º 5
0
		private void OnButtonClick()
		{
			requestCode++;

			// Build PendingIntent
			var pendingIntent = MakePendingIntent();

			var replyText = GetString(Resource.String.reply_text);

			// Create remote input that will read text
			var remoteInput = new Android.Support.V4.App.RemoteInput.Builder(KEY_TEXT_REPLY)
										 .SetLabel(replyText)
										 .Build();

			// Build action for noticiation
			var action = new NotificationCompat.Action.Builder(Resource.Drawable.action_reply, replyText, pendingIntent)
											   .AddRemoteInput(remoteInput)
											   .Build();

			// Build notification
			var notification = new NotificationCompat.Builder(this)
													 .SetSmallIcon(Resource.Drawable.reply)
													 .SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.avatar))
													 .SetContentText("Hey, it is James! What's up?")
													 .SetContentTitle(GetString(Resource.String.message))
													 .SetAutoCancel(true)
													 .AddAction(action)
													 .Build();

			// Notify
			using (var notificationManager = NotificationManagerCompat.From(this))
			{
				notificationManager.Notify(requestCode, notification);
			}
		}
		public override void OnReceive (Context context, Intent intent) {
			if (RetreiveLatestReceiver.IsAvailableVersion(context)) {
				intent.PutExtra ("title", string.Format(context.Resources.GetString(Resource.String.notification_title), "WhatsApp " + RetreiveLatestReceiver.GetLatestVersion ()));
				intent.PutExtra ("message", string.Format(context.Resources.GetString(Resource.String.notification_description), context.Resources.GetString(Resource.String.app_name)));
				var message = intent.GetStringExtra ("message");
				var title = intent.GetStringExtra ("title");

				var notIntent = new Intent (context, typeof(MainActivity));
				var contentIntent = PendingIntent.GetActivity (context, 0, notIntent, PendingIntentFlags.CancelCurrent);
				var manager = NotificationManagerCompat.From (context);

				var style = new NotificationCompat.BigTextStyle ().BigText (message);
				int resourceId = Resource.Drawable.ic_launcher;

				var wearableExtender = new NotificationCompat.WearableExtender ().SetBackground (BitmapFactory.DecodeResource (context.Resources, resourceId));

				// Generate notification (short text and small icon)
				var builder = new NotificationCompat.Builder (context);
				builder.SetContentIntent (contentIntent);
				builder.SetSmallIcon (Resource.Drawable.ic_launcher);
				builder.SetContentTitle (title);
				builder.SetContentText (message);
				builder.SetStyle (style);
				builder.SetWhen (Java.Lang.JavaSystem.CurrentTimeMillis ()); // When the AlarmManager will check changes?
				builder.SetAutoCancel (true);
				builder.Extend (wearableExtender); // Support Android Wear, yeah!

				var notification = builder.Build ();
				manager.Notify (0, notification);
			}
		}
Ejemplo n.º 7
0
        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            var LocationServiceIntent = new Intent ("com.ETCTimeApp.SaveLocationService");
            pendingSaveLocationServiceIntent = PendingIntent.GetService (this, 0, LocationServiceIntent, 0);
            alarm = (AlarmManager)this.BaseContext.GetSystemService (Context.AlarmService);
            //repeat every 10 minutes
            alarm.SetRepeating (AlarmType.RtcWakeup,
                10000,
                1 * 5000 * 60,
                pendingSaveLocationServiceIntent);

            var pendingIntent = PendingIntent.GetActivity (this, 1, new Intent (this, typeof(MainActivity)), 0);
            var resultString = "Location service is running on background!";

            int ic_small = Resource.Drawable.gps_small;
            var builder = new NotificationCompat.Builder (this)
                .SetAutoCancel (true)
                .SetContentIntent (pendingIntent)
                .SetContentTitle ("ETC Location Notification")
                .SetSmallIcon (ic_small)
                .SetContentText (resultString);

            // start our service foregrounded, that way it won't get cleaned up from memory pressure
            StartForeground ((int)NotificationFlags.ForegroundService, builder.Build ());

            return StartCommandResult.Sticky;
        }
Ejemplo n.º 8
0
		protected override void OnHandleIntent (Intent intent)
		{
			Android.Util.Log.Info ("CytotemGeofence", "Got geofence intent");

			var geofencingEvent = GeofencingEvent.FromIntent (intent);
			if (geofencingEvent.HasError) {
				var errorMessage = GeofenceStatusCodes.GetStatusCodeString (geofencingEvent.ErrorCode);
				Android.Util.Log.Error ("CytotemGeofence", errorMessage);
				return;
			}

			if (geofencingEvent.GeofenceTransition == Geofence.GeofenceTransitionEnter) {
				Android.Util.Log.Info ("CytotemGeofence", "Adding geofence occurence at " + DateTime.Now.ToString ());

				var db = GeofenceDatabase.From (this);
				AddOccurence (db);

				var activityIntent = new Intent (this, typeof (MainActivity));
				var notification = new NotificationCompat.Builder (this)
					.SetSmallIcon (Resource.Drawable.ic_notification)
					.SetContentTitle ("Broadway totem hit")
					.SetContentText ("You passed by the bike totem at " + DateTime.Now.ToShortTimeString ())
					.SetContentIntent (PendingIntent.GetActivity (this, 0, activityIntent, PendingIntentFlags.UpdateCurrent))
					.Build ();
				NotificationManagerCompat.From (this).Notify (0, notification);
			}
		}
		public void ShowLocalNotification ()
		{
			// Pass value to the next form:
			// Bundle valuesForActivity = new Bundle();
			// valuesForActivity.PutInt("count", count);

			// When the user clicks the notification, SecondActivity will start up.
			//Intent resultIntent = new Intent(this, typeof(SecondActivity));

			// Pass some values to SecondActivity:
			//resultIntent.PutExtras(valuesForActivity); 

			var ctx = Forms.Context;

			// Build the notification:
			NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx)
				.SetAutoCancel(true)                    // Dismiss the notification from the notification area when the user clicks on it

				.SetContentTitle("Title Notification")      // Set the title
				.SetSmallIcon(Resource.Drawable.icon) // This is the icon to display
				.SetContentText(String.Format("Message Notification")); // the message to display.

			// Finally, publish the notification:
			NotificationManager notificationManager = (NotificationManager)ctx.GetSystemService(Context.NotificationService);
			notificationManager.Notify(notificationId, builder.Build());
		}
Ejemplo n.º 10
0
    IEnumerator Load()
    {
        NotificationManager manager = NotificationManager.GetNotificationManager();
        NotificationCompat.Builder builder = new NotificationCompat.Builder();

        builder.SetContentTitle("必要なデータのダウンロード");
        builder.SetContentText("ダウンロード中です");
        builder.SetTicker("ダウンロード中です");
        builder.SetSmallIcon();
        builder.SetProgress(100, 0, true);

        manager.Notify(0, builder.Build());

        www = new WWW("https://dl.dropboxusercontent.com/u/153254465/Unity%E7%B3%BB/test.unity3d");

        while (!www.isDone && www.error == null)
        {
            builder.SetProgress(100, (int)(www.progress * 100), true);
            builder.SetNumber((int)(www.progress * 100));
            manager.Notify(0, builder.Build());
            yield return new WaitForEndOfFrame();
        }
        builder.SetProgress(0, 0, false);
        Notification.Default defauls = Notification.Default.Sound | Notification.Default.Vibrate;
        builder.SetDefaults(defauls);
        builder.SetTicker("ダウンロードが完了しました");
        builder.SetContentText("ダウンロードが完了しました");
        builder.SetContentIntent();
        manager.Notify(0, builder.Build());
    }
Ejemplo n.º 11
0
		private void ButtonOnClick (object sender, EventArgs eventArgs)
		{
			// These are the values that we want to pass to the next activity
			Bundle valuesForActivity = new Bundle ();
			valuesForActivity.PutInt ("count", _count);

			// Create the PendingIntent with the back stack             
			// When the user clicks the notification, SecondActivity will start up.
			Intent resultIntent = new Intent (this, typeof(SecondActivity));
			resultIntent.PutExtras (valuesForActivity); // Pass some values to SecondActivity.

			TaskStackBuilder stackBuilder = TaskStackBuilder.Create (this);
			stackBuilder.AddParentStack (Class.FromType (typeof(SecondActivity)));
			stackBuilder.AddNextIntent (resultIntent);

			PendingIntent resultPendingIntent = stackBuilder.GetPendingIntent (0, (int)PendingIntentFlags.UpdateCurrent);

			// Build the notification
			NotificationCompat.Builder builder = new NotificationCompat.Builder (this)
                .SetAutoCancel (true) // dismiss the notification from the notification area when the user clicks on it
                .SetContentIntent (resultPendingIntent) // start up this activity when the user clicks the intent.
                .SetContentTitle ("Button Clicked") // Set the title
                .SetNumber (_count) // Display the count in the Content Info
                .SetSmallIcon (Resource.Drawable.ic_stat_button_click) // This is the icon to display
                .SetContentText (String.Format ("The button has been clicked {0} times.", _count)); // the message to display.

			// Finally publish the notification
			NotificationManager notificationManager = (NotificationManager)GetSystemService (NotificationService);
			notificationManager.Notify (ButtonClickNotificationId, builder.Build ());

			_count++;
		}
Ejemplo n.º 12
0
		private void CreateNotification(Intent intent) {
			recipe = Recipe.FromBundle(intent.GetBundleExtra(Constants.ExtraRecipe));
			List<Notification> notificationPages = new List<Notification> ();

			int stepCount = recipe.RecipeSteps.Count;

			for (int i = 0; i < stepCount; i++) {
				Recipe.RecipeStep recipeStep = recipe.RecipeSteps [i];
				var style = new NotificationCompat.BigTextStyle ();
				style.BigText (recipeStep.StepText);
				style.SetBigContentTitle (String.Format (Resources.GetString (Resource.String.step_count), i + 1, stepCount));
				style.SetSummaryText ("");
				var builder = new NotificationCompat.Builder (this);
				builder.SetStyle (style);
				notificationPages.Add (builder.Build ());
			}

			var notifBuilder = new NotificationCompat.Builder(this);

			if (recipe.RecipeImage != null) {
				Bitmap recipeImage = Bitmap.CreateScaledBitmap(
					AssetUtils.LoadBitmapAsset(this, recipe.RecipeImage),
					Constants.NotificationImageWidth, Constants.NotificationImageHeight, false);
				notifBuilder.SetLargeIcon(recipeImage);
			}
			notifBuilder.SetContentTitle (recipe.TitleText);
			notifBuilder.SetContentText (recipe.SummaryText);
			notifBuilder.SetSmallIcon (Resource.Mipmap.ic_notification_recipe);

			Notification notification = notifBuilder.Extend(new NotificationCompat.WearableExtender().AddPages(notificationPages)).Build();
			notificationManager.Notify (Constants.NotificationId, notification);
		}
Ejemplo n.º 13
0
		public override void OnReceive (Context context, Intent intent)
		{
			var message = intent.GetStringExtra("message");
			var title = intent.GetStringExtra("title");

			var notIntent = new Intent(context, typeof(MainScreen));
			var contentIntent = PendingIntent.GetActivity(context, 0, notIntent, PendingIntentFlags.CancelCurrent);
			var manager = NotificationManagerCompat.From(context);

			var style = new NotificationCompat.BigTextStyle();
			style.BigText(message);

			int resourceId = Resource.Drawable.HappyBaby;

			var wearableExtender = new NotificationCompat.WearableExtender()
				.SetBackground(BitmapFactory.DecodeResource(context.Resources, resourceId));

			//Generate a notification with just short text and small icon
			var builder = new NotificationCompat.Builder(context)
				.SetContentIntent(contentIntent)
				.SetSmallIcon(Resource.Drawable.HappyBaby)
				.SetSound(Android.Net.Uri.Parse("android.resource://com.iinotification.app/"+ Resource.Raw.babySound))
				.SetContentTitle("Hey Mom")
				.SetContentText("Here I'm :)")
				.SetStyle(style)
				.SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis())
				.SetAutoCancel(true)
				.Extend(wearableExtender);

			var notification = builder.Build();
			manager.Notify(0, notification);
		}
		protected override void OnHandleIntent (Intent intent)
		{
			Context context = ApplicationContext;
			// var alarm = (Alarm)intent.GetParcelableExtra (ALARM_KEY);

			// TODO - workaround https://github.com/googlesamples/android-DirectBoot/issues/4
			Bundle bundle = intent.Extras;
			var alarm = new Alarm {
				Id = bundle.GetInt ("id"),
				Year = bundle.GetInt ("year"),
				Month = bundle.GetInt ("month"),
				Day = bundle.GetInt ("day"),
				Hour = bundle.GetInt ("hour"),
				Minute = bundle.GetInt ("minute")
			};

			var manager = context.GetSystemService (NotificationService).JavaCast<NotificationManager> ();
			var builder = new NotificationCompat.Builder (context)
												.SetSmallIcon (Resource.Drawable.ic_fbe_notification)
												.SetCategory (Notification.CategoryAlarm)
												.SetSound (Settings.System.DefaultAlarmAlertUri)
												.SetContentTitle (context.GetString (Resource.String.alarm_went_off, alarm.Hour, alarm.Minute));

			manager.Notify (alarm.Id, builder.Build ());
			var alarmStorage = new AlarmStorage (context);
			alarmStorage.DeleteAlarm (alarm);

			var wentoffIntent = new Intent (ALARM_WENT_OFF_ACTION);
			wentoffIntent.PutExtra (ALARM_KEY, alarm);
			LocalBroadcastManager.GetInstance (context).SendBroadcast (wentoffIntent);
		}
Ejemplo n.º 15
0
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Android.OS.Bundle savedInstanceState)
        {
            var ignored = base.OnCreateView(inflater, container, savedInstanceState);
            var view = inflater.Inflate(Resource.Layout.fragment_profile, null);
            imageLoader = new ImageLoader(Activity);
            view.FindViewById<TextView>(Resource.Id.profile_name).Text = "James Montemagno";
			view.FindViewById<TextView>(Resource.Id.profile_description).Text = "James Montemagno is a Developer Evangelist at Xamarin and Microsoft MVP. He has been a .NET developer for over a decade working in a wide range of industries and before joining Xamarin was a professional mobile developer on the Xamarin platform for over 4 years. He can be found on Twitter @JamesMontemagno and blogs regularly at  www.MotzCod.es";
			imageLoader.DisplayImage("https://pbs.twimg.com/profile_images/618564939523862528/TMHi-4M-.jpg", view.FindViewById<ImageView>(Resource.Id.profile_image), -1);

            view.FindViewById<ImageView>(Resource.Id.profile_image).Click += (sender, args) =>
                {
                    var builder = new NotificationCompat.Builder(Activity)
                    .SetSmallIcon(Resource.Drawable.ic_launcher)
                    .SetContentTitle("Click to go to friend details!")
                    .SetContentText("New Friend!!");
                            
                    var friendActivity = new Intent(Activity, typeof(FriendActivity));

                    PendingIntent pendingIntent = PendingIntent.GetActivity(Activity, 0, friendActivity, 0);
                  

                    builder.SetContentIntent(pendingIntent);
                    builder.SetAutoCancel(true);
                    var notificationManager = 
                        (NotificationManager) Activity.GetSystemService(Context.NotificationService);
                    notificationManager.Notify(0, builder.Build());
                };
            return view;
        }
Ejemplo n.º 16
0
		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);

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

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

			//button click Event
			button.Click += delegate {
				//star a new Mservice to cach music info
				StartService(new Intent(this, typeof(Mservice)));
				//Show tast message
				Toast.MakeText(this,"Music Service Started¡¡¡¡",ToastLength.Short).Show();
			};
			//Inicialize Notification builder
			builder = new NotificationCompat.Builder (this)
				.SetContentTitle (this.Title)
				.SetSmallIcon(Resource.Drawable.ic_launcher)
				.SetContentText (this.Title);
			//Set persistent notification 
			builder.SetOngoing (true);
			//Get notification manager service
			notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);
		}
Ejemplo n.º 17
0
        protected override void OnMessage (Context context, Intent intent)
        {
            //Push Notification arrived - print out the keys/values
            Intent received = new Intent (context, typeof(RecievedPush));
            string pushMessage = intent.GetStringExtra ("message");
            received.AddFlags (ActivityFlags.ReorderToFront);
            received.AddFlags (ActivityFlags.NewTask);
            received.PutExtra ("pushedMessage", pushMessage);
            if (intent == null || intent.Extras == null) {
                received.PutExtras (intent.Extras);
                foreach (var key in intent.Extras.KeySet()) {
                    Console.WriteLine ("Key: {0}, Value: {1}");
                }
            }
            PendingIntent notificationLaunch = PendingIntent.GetActivity (context, 1000, received, PendingIntentFlags.CancelCurrent );
            NotificationManager manager = (NotificationManager)GetSystemService (Context.NotificationService);
            NotificationCompat.Builder builder = new NotificationCompat.Builder (context);
            builder.SetContentText (pushMessage);
            builder.SetContentIntent ( notificationLaunch);
            builder.SetContentTitle ("New Message");
            builder.SetSmallIcon (Resource.Drawable.ic_action_chat);
            builder.SetStyle ( new NotificationCompat.InboxStyle());
            builder.SetSound (RingtoneManager.GetDefaultUri (RingtoneType.Notification));
            builder.SetVibrate (new long[] { 500, 300, 100, 1000, 300, 300, 300 ,300 });
            manager.Notify (1000, builder.Build ());

            Buddy.RecordNotificationReceived(intent);
         
        }
        /// <summary>
        /// Show a local notification in the Notification Area and Drawer.
        /// </summary>
        /// <param name="title">Title of the notification</param>
        /// <param name="body">Body or description of the notification</param>
        /// <param name="id">Id of notifications</param>
        public void Show(string title, string body, int id = 0)
        {
            var builder = new NotificationCompat.Builder(Application.Context);
            builder.SetContentTitle(title);
            builder.SetContentText(body);
            builder.SetAutoCancel(true);

            if (NotificationIconId != 0)
            {
                builder.SetSmallIcon(NotificationIconId);
            }
            else
            {
                builder.SetSmallIcon(Resource.Drawable.plugin_lc_smallicon);
            }

            var resultIntent = GetLauncherActivity();
            resultIntent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);
            var stackBuilder = Android.Support.V4.App.TaskStackBuilder.Create(Application.Context);
            stackBuilder.AddNextIntent(resultIntent);
            var resultPendingIntent =
                stackBuilder.GetPendingIntent(0, (int)PendingIntentFlags.UpdateCurrent);
            builder.SetContentIntent(resultPendingIntent);

            var notificationManager = NotificationManagerCompat.From(Application.Context);
            notificationManager.Notify(id, builder.Build());
        }
Ejemplo n.º 19
0
        private void ShowNotification(string message)
        {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this.context)
                .SetContentTitle("CallMinder detected call")
                    .SetSmallIcon(Android.Resource.Drawable.SymActionCall)
                    .SetContentText(message);

            NotificationManager notificationManager = (NotificationManager) this.context.GetSystemService(Context.NotificationService);
            notificationManager.Notify(101, builder.Build());
        }
Ejemplo n.º 20
0
		public void Show (string message)
		{
			var builder = new NotificationCompat.Builder (Forms.Context)
				.SetAutoCancel (true)                    
				.SetContentTitle ("Button Clicked")    
				.SetSmallIcon (Resource.Drawable.icon)  
				.SetContentText (message);

			var notificationManager = (NotificationManager)Forms.Context.GetSystemService (Context.NotificationService);
			notificationManager.Notify (NotificationId, builder.Build ());
		}
Ejemplo n.º 21
0
        public void CallWebService()
        {
            _timer = new System.Threading.Timer(async (o) =>
                {
                    var dadosAPI = await CallAPI_Droid.ExecChamadaAPIComRetornoString(EnumCallAPI.Promo);

                    if (String.IsNullOrEmpty(dadosAPI))
                        return;

                    // Configurando URL recebida pelo serviço
                    var xmlString = this.XMLDeserialization(dadosAPI);

                    App.URL = xmlString.Text.Split(',')[0];

                    // Salvando imagem e carregando o Bitmap
                    var saveImage = new SaveAndLoadFile_Droid();
                    var imageName = String.Concat(System.IO.Path.GetRandomFileName().Split('.')[0], ".jpg");
                    Bitmap bmpImagem = null;

                    if (saveImage.BaixaImagemSalvarEmDisco(imageName, xmlString.Text.Split(',')[1]))
                        bmpImagem = BitmapFactory.DecodeFile(saveImage.GetImage(imageName));

                    // Construindo Intent para carregamento da Activity
                    var intent = new Intent(this, typeof(MainActivity));

                    // Construindo PendingIntent
                    const int pendingIntentID = 0;
                    var pendingIntent = PendingIntent.GetActivity(this, pendingIntentID, intent, PendingIntentFlags.OneShot);

                    // Construindo a notificação
                    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                        .SetContentIntent(pendingIntent)
                        .SetAutoCancel(true)
                        .SetContentTitle("Nova Promoção")
                        .SetSmallIcon(Resource.Drawable.ic_stat_bu_bling)
                        .SetContentText("Clique aqui para ter acesso a nova promoção");

                    if (bmpImagem != null && bmpImagem.ByteCount > 0)
                        builder.SetLargeIcon(bmpImagem);

                    if ((int)Android.OS.Build.VERSION.SdkInt >= 21)
                    {
                        builder.SetVisibility(0);
                        builder.SetCategory(Android.App.Notification.CategoryPromo);
                    }

                    // Publicando a notificação
                    NotificationManager notificationManager =
                        (NotificationManager)GetSystemService("notification");
                    notificationManager.Notify(10, builder.Build());

                }, null, 0, 1800000);
        }
 protected override void OnHandleIntent(Intent intent)
 {
     bool isEntering= intent.GetBooleanExtra(LocationManager.KeyProximityEntering, false);
     NotificationCompat.Builder builder = new NotificationCompat.Builder (this);
     var notification = builder
         .SetContentTitle("TODO")
         .SetContentText((isEntering? "Entering" : "Exiting") + " fence")
         .Build();
     var notificationService = (NotificationManager)GetSystemService (Context.NotificationService);
     notificationService.Notify (1, notification);
     int i = 17;
     //TODO: check LocationManager.KEY_PROXIMITY
 }
Ejemplo n.º 23
0
		public void OnTimerSelected (View v)
		{
			v.Pressed = true;
			Notification notification = new NotificationCompat.Builder (this)
				.SetSmallIcon (Resource.Drawable.ic_launcher)
				.SetContentTitle (GetString (Resource.String.notification_title))
				.SetContentText (GetString (Resource.String.notification_timer_selected))
				.Build ();
			NotificationManagerCompat.From (this).Notify (0, notification);
			SendMessageToCompanion (TIMER_SELECTED_PATH);
			// Prevent onTimerFinished from being heard.
			((DelayedConfirmationView)v).SetListener (null);
			Finish (); 
		}
Ejemplo n.º 24
0
		void BuildLocalOnlyNotification(string title, string content, int notificationId, bool withDismissal) {
			NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
			builder.SetContentTitle (title)
				.SetContentText (content)
				.SetLocalOnly (true)
				.SetSmallIcon (Resource.Drawable.ic_launcher);

			if (withDismissal) {
				Intent dismissalIntent = new Intent (Constants.ActionDismiss);
				dismissalIntent.PutExtra (Constants.KeyNotificationId, Constants.BothId);
				PendingIntent pendingIndent = PendingIntent.GetService (this, 0, dismissalIntent, PendingIntentFlags.UpdateCurrent);
				builder.SetDeleteIntent(pendingIndent);
			}
			NotificationManagerCompat.From (this).Notify (notificationId, builder.Build ());
		}
Ejemplo n.º 25
0
		public void ShowNotification (View view)
		{
			var notification = new NotificationCompat.Builder (this)
				.SetContentTitle (GetString (Resource.String.notification_title))
				.SetContentText (GetString (Resource.String.notification_title))
				.SetSmallIcon (Resource.Drawable.ic_launcher)
				.AddAction (Resource.Drawable.ic_launcher,
				                   GetText (Resource.String.action_launch_activity),
				                   PendingIntent.GetActivity (this, NOTIFICATION_REQUEST_CODE,
					                   new Intent (this, typeof(GridExampleActivity)),
					                   PendingIntentFlags.UpdateCurrent))
				.Build ();
			NotificationManagerCompat.From (this).Notify (NOTIFICATION_ID, notification);
			Finish ();
		}
		/**
		* Adds a new {@link Notification} with sample data and sends it to the system.
		* Then updates the current number of displayed notifications for this application and
		* creates a notification summary if more than one notification exists.
		*/
		void AddNotificationAndUpdateSummaries ()
		{
			// Create a Notification and notify the system.
			var builder = new NotificationCompat.Builder (Activity)
				.SetSmallIcon (Resource.Mipmap.ic_notification)
				.SetContentTitle (GetString (Resource.String.app_name))
				.SetContentText (GetString (Resource.String.sample_notification_content))
				.SetAutoCancel (true)
				.SetDeleteIntent (deletePendingIntent)
				.SetGroup (NOTIFICATION_GROUP);

			Notification notification = builder.Build ();
			notificationManager.Notify (GetNewNotificationId (), notification);

			CommonSampleLibrary.Log.Info (TAG, "Add a notification");
			UpdateNotificationSummary ();
			UpdateNumberOfNotifications ();
		}
Ejemplo n.º 27
0
		private void SendNotification (string titles, string texts, string minimizedContent)
		{
			PendingIntent contentIntent = PendingIntent.GetActivity(this, 0,
				new Intent(this, typeof(MainActivity)), PendingIntentFlags.UpdateCurrent);

			NotificationCompat.Builder notiBuild = new NotificationCompat.Builder (this)
				.SetAutoCancel (false)
				.SetContentTitle (titles)
				.SetContentText (minimizedContent)
				.SetSmallIcon(Resource.Mipmap.ic_launcher)
				.SetTicker ("API Update")
				.SetStyle(new NotificationCompat.BigTextStyle().BigText(texts))
				.SetOngoing(true)
				.SetContentIntent(contentIntent);

			NotificationManager notiManager = (NotificationManager)GetSystemService (Context.NotificationService);
			notiManager.Notify (notiId, notiBuild.Build());
		}
        void SendNotification(string message)
        {
            var intent = new Intent (this, typeof(MainActivity));
            intent.AddFlags (ActivityFlags.ClearTop);
            var pendingIntent = PendingIntent.GetActivity (this, 0, intent, PendingIntentFlags.OneShot);

            var defaultSoundUri = RingtoneManager.GetDefaultUri (RingtoneType.Notification);

            var notificationBuilder = new NotificationCompat.Builder (this)
                .SetSmallIcon (Resource.Drawable.ic_stat_ic_notification)
                .SetContentTitle ("GCM Message")
                .SetContentText (message)
                .SetAutoCancel (true)
                .SetSound (defaultSoundUri)
                .SetContentIntent (pendingIntent);

            var notificationManager = (NotificationManager)GetSystemService (Context.NotificationService);
            notificationManager.Notify (0, notificationBuilder.Build ());
        }
Ejemplo n.º 29
0
        public override void ProcessNotification(Context context, string notificationType, string json)
        {
            var manager =
                    (NotificationManager)context.GetSystemService(Context.NotificationService);

            var intent =
                context.PackageManager.GetLaunchIntentForPackage(context.PackageName);
            intent.AddFlags(ActivityFlags.ClearTop);

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

            var builder = new NotificationCompat.Builder(context)
                .SetSmallIcon(Android.Resource.Drawable.StarBigOn)
                .SetContentTitle("Boop!")
                .SetStyle(new NotificationCompat.BigTextStyle().BigText(json))
                .SetContentText(json)
                .SetContentIntent(pendingIntent);

            manager.Notify(1, builder.Build());
        }
Ejemplo n.º 30
0
        void ParsePush_ParsePushNotificationReceived(object sender, ParsePushNotificationEventArgs e)
        {
            var intent = new Intent(Context, typeof(MainActivity));
            PendingIntent pendingIntent = PendingIntent.GetActivity(Context, 0, intent, PendingIntentFlags.OneShot);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(Context)
                .SetContentTitle("Doorduino")
                .SetAutoCancel(true)
                .SetContentText(e.Payload["alert"].ToString())
                .SetPriority((int)NotificationPriority.High)
                .SetVisibility((int)NotificationVisibility.Public)
                .SetCategory(Notification.CategoryAlarm)
                .SetContentIntent(pendingIntent)
                .SetDefaults((int)(NotificationDefaults.Sound | NotificationDefaults.Vibrate))
                .SetSmallIcon(Android.Resource.Drawable.IcMenuSend);

            var notification = builder.Build();
            var notificationManager = (NotificationManager)Context.GetSystemService(Context.NotificationService);
            notificationManager.Notify(0, notification);
        }
Ejemplo n.º 31
0
        private void SendNotification(string notificationJson)
        {
            try
            {
                var block = AdaptiveBlock.Parse(notificationJson).Block;

                var content = block?.View?.Content;
                if (content != null)
                {
                    var builder = new NotificationCompat.Builder(this, AppClient.CHANNEL_ID)
                                  .SetSmallIcon(Android.Resource.Drawable.abc_btn_switch_to_on_mtrl_00001)
                                  .SetAutoCancel(true)
                                  .SetPriority(1);

                    if (content.Title != null)
                    {
                        builder.SetContentTitle(content.Title);
                    }

                    if (content.Subtitle != null)
                    {
                        builder.SetContentText(content.Subtitle);
                        builder.SetStyle(new NotificationCompat.BigTextStyle()
                                         .BigText(content.Subtitle));
                    }

                    var profileImg = GetBitmap(content.GetProfileImage());
                    var heroImg    = GetBitmap(content.GetHeroImage());

                    if (heroImg != null)
                    {
                        builder.SetLargeIcon(heroImg);

                        builder.SetStyle(new NotificationCompat.BigPictureStyle()
                                         .BigPicture(heroImg)
                                         .BigLargeIcon(profileImg));
                    }
                    else
                    {
                        if (profileImg != null)
                        {
                            builder.SetLargeIcon(profileImg);
                        }

                        // Expandable
                        builder.SetStyle(new NotificationCompat.BigTextStyle()
                                         .BigText(content.Subtitle));
                    }

                    foreach (var action in content.GetSimplifiedActions())
                    {
                        if ((action.Inputs.Count == 0 || action.Inputs.Count == 1 && action.Inputs[0] is AdaptiveTextInputBlock) && action.Command != null)
                        {
                            PendingIntent pendingIntent;
                            if (action.Command is AdaptiveOpenUrlCommand openUrlCommand)
                            {
                                Intent openUrlIntent = new Intent(Intent.ActionView, global::Android.Net.Uri.Parse(openUrlCommand.Url));
                                pendingIntent = PendingIntent.GetActivity(this, 0, openUrlIntent, 0);
                            }
                            else
                            {
                                Intent actionIntent = new Intent(this, typeof(NotificationActionReceiver));
                                actionIntent.SetAction("com.microsoft.InteractiveNotifs.ApiClient.Android.InvokeAction");
                                actionIntent.PutExtra("cmd", JsonConvert.SerializeObject(action.Command));
                                if (action.Inputs.FirstOrDefault() is AdaptiveTextInputBlock tbInputBlock)
                                {
                                    actionIntent.PutExtra("textId", tbInputBlock.Id);
                                }
                                pendingIntent = PendingIntent.GetBroadcast(this, new Random().Next(int.MaxValue), actionIntent, PendingIntentFlags.OneShot);
                            }

                            if (action.Inputs.FirstOrDefault() is AdaptiveTextInputBlock tbInput)
                            {
                                var remoteInput = new global::Android.Support.V4.App.RemoteInput.Builder("text")
                                                  .SetLabel(tbInput.Placeholder ?? action.Title)
                                                  .Build();

                                builder.AddAction(new NotificationCompat.Action.Builder(
                                                      Resource.Drawable.abc_ic_go_search_api_material,
                                                      action.Title,
                                                      pendingIntent)
                                                  .AddRemoteInput(remoteInput)
                                                  .Build());
                            }
                            else
                            {
                                builder.AddAction(Android.Resource.Drawable.abc_btn_check_material, action.Title, pendingIntent);
                            }
                        }
                    }

                    var manager = NotificationManagerCompat.From(this);
                    manager.Notify(1, builder.Build());
                }
            }
            catch { }
        }
Ejemplo n.º 32
0
        private void Location_LocationRequested(object source, EventArgs args)
        {
            Log.Error("Locatie preluata in service", "here");
            try {
                if (_pacientLatitude == 0 || _pacientLongitude == 0)
                {
                    _pacientLatitude  = ((LocationEventArgs)args).Location.Latitude;
                    _pacientLongitude = ((LocationEventArgs)args).Location.Longitude;
                }
                Log.Error("Patient", $"{_pacientLatitude},{_pacientLongitude}");
                Log.Error("Asistent", $"{((LocationEventArgs)args).Location.Latitude},{((LocationEventArgs)args).Location.Longitude}");


                if (!Utils.GetDefaults("ActivityStart").Equals(string.Empty))
                {
                    double distance = Utils.HaversineFormula(_pacientLatitude, _pacientLongitude,
                                                             ((LocationEventArgs)args).Location.Latitude, ((LocationEventArgs)args).Location.Longitude);
                    Log.Error("Distance", "" + distance);
                    Toast.MakeText(this, Math.Round(distance) + " metri.", ToastLength.Short)
                    .Show();
                    if (distance > 450 && distance < 550)
                    {
                        Log.Warn("Distance warning",
                                 "mai mult de 200 metri. Esti la " + Math.Round(distance) + " metri distanta");
                        _verifications = 0;
                        NotificationCompat.Builder nb = GetAndroidChannelNotification("Avertisment",
                                                                                      "Ai plecat de la pacient? Esti la " + Math.Round(distance) + " metri distanta");

                        GetManager().Notify(2, nb.Build());
                        if (_refreshTime == 15000)
                        {
                            return;
                        }
                        _refreshTime = 15000;
                        location.ChangeInterval(_refreshTime);
                    }
                    else if (distance >= 550)
                    {
                        if (_verifications == 0)
                        {
                            NotificationCompat.Builder nb =
                                GetAndroidChannelNotification("Avertisment", "Vizita a fost anulata automat!");
                            GetManager().Notify(2, nb.Build());
                            //trimitere date la server
                            Utils.SetDefaults("ActivityStart", string.Empty);
                            Utils.SetDefaults("QrId", string.Empty);
                            Utils.SetDefaults("QrCode", string.Empty);
                            Utils.SetDefaults("readedQR", string.Empty);
                            StopSelf();
                        }
                        else
                        {
                            NotificationCompat.Builder nb = GetAndroidChannelNotification("Avertisment",
                                                                                          "Vizita va fi anulata automat deoarece te afli la " + (Math.Round(distance) > 1000 ? (Math.Round(distance) / 1000).ToString().Replace('.', ',') + " kilometri" : Math.Round(distance) + " metri") +
                                                                                          " distanta de pacient! Mai ai " + (_verifications) +
                                                                                          " minute sa te intorci!");
                            GetManager().Notify(2, nb.Build());
                            _verifications--;
                            if (_refreshTime == 60000)
                            {
                                return;
                            }
                            _refreshTime = 60000;
                            location.ChangeInterval(_refreshTime);
                        }
                    }
                    else
                    {
                        _verifications = 15;

                        if (_refreshTime == 15000)
                        {
                            return;
                        }
                        _refreshTime = 15000;
                        location.ChangeInterval(_refreshTime);
                    }
                }
                else
                {
                    Utils.SetDefaults("ActivityStart", string.Empty);
                    Utils.SetDefaults("QrId", string.Empty);
                    Utils.SetDefaults("QrCode", string.Empty);
                    Utils.SetDefaults("readedQR", string.Empty);
                    StopSelf();
                }
            } catch (Exception e) {
                Log.Error($"Error occurred in {nameof(DistanceCalculator)} service: ", e.Message);
                Utils.SetDefaults("ActivityStart", string.Empty);
                Utils.SetDefaults("QrId", string.Empty);
                Utils.SetDefaults("QrCode", string.Empty);
                Utils.SetDefaults("readedQR", string.Empty);
                StopSelf();
            }
        }
Ejemplo n.º 33
0
        //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 (notification.BadgeCount != null)
            {
                builder.SetNumber(notification.BadgeCount.Value);
            }

            //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));
        }
Ejemplo n.º 34
0
        public void OnReceived(IDictionary <string, string> parameters)
        {
            System.Diagnostics.Debug.WriteLine($"{DomainTag} - OnReceived");

            if (parameters.ContainsKey(SilentKey) && (parameters[SilentKey] == "true" || parameters[SilentKey] == "1"))
            {
                return;
            }

            Context context = Android.App.Application.Context;

            int    notifyId = 0;
            string title    = context.ApplicationInfo.LoadLabel(context.PackageManager);
            string message  = "";
            string tag      = "";

            if (!string.IsNullOrEmpty(FirebasePushNotificationManager.NotificationContentTextKey) && parameters.ContainsKey(FirebasePushNotificationManager.NotificationContentTextKey))
            {
                message = parameters[FirebasePushNotificationManager.NotificationContentTextKey].ToString();
            }
            else if (parameters.ContainsKey(AlertKey))
            {
                message = $"{parameters[AlertKey]}";
            }
            else if (parameters.ContainsKey(BodyKey))
            {
                message = $"{parameters[BodyKey]}";
            }
            else if (parameters.ContainsKey(MessageKey))
            {
                message = $"{parameters[MessageKey]}";
            }
            else if (parameters.ContainsKey(SubtitleKey))
            {
                message = $"{parameters[SubtitleKey]}";
            }
            else if (parameters.ContainsKey(TextKey))
            {
                message = $"{parameters[TextKey]}";
            }

            if (!string.IsNullOrEmpty(FirebasePushNotificationManager.NotificationContentTitleKey) && parameters.ContainsKey(FirebasePushNotificationManager.NotificationContentTitleKey))
            {
                title = parameters[FirebasePushNotificationManager.NotificationContentTitleKey].ToString();
            }
            else if (parameters.ContainsKey(TitleKey))
            {
                if (!string.IsNullOrEmpty(message))
                {
                    title = $"{parameters[TitleKey]}";
                }
                else
                {
                    message = $"{parameters[TitleKey]}";
                }
            }



            if (parameters.ContainsKey(IdKey))
            {
                var str = parameters[IdKey].ToString();
                try
                {
                    notifyId = Convert.ToInt32(str);
                }
                catch (System.Exception ex)
                {
                    // Keep the default value of zero for the notify_id, but log the conversion problem.
                    System.Diagnostics.Debug.WriteLine("Failed to convert {0} to an integer", str);
                }
            }
            if (parameters.ContainsKey(TagKey))
            {
                tag = parameters[TagKey].ToString();
            }

            if (FirebasePushNotificationManager.SoundUri == null)
            {
                FirebasePushNotificationManager.SoundUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
            }
            try
            {
                if (FirebasePushNotificationManager.IconResource == 0)
                {
                    FirebasePushNotificationManager.IconResource = context.ApplicationInfo.Icon;
                }
                else
                {
                    string name = context.Resources.GetResourceName(FirebasePushNotificationManager.IconResource);

                    if (name == null)
                    {
                        FirebasePushNotificationManager.IconResource = context.ApplicationInfo.Icon;
                    }
                }
            }
            catch (Android.Content.Res.Resources.NotFoundException ex)
            {
                FirebasePushNotificationManager.IconResource = context.ApplicationInfo.Icon;
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }


            Intent resultIntent = context.PackageManager.GetLaunchIntentForPackage(context.PackageName);

            //Intent resultIntent = new Intent(context, typeof(T));
            Bundle extras = new Bundle();

            foreach (var p in parameters)
            {
                extras.PutString(p.Key, p.Value);
            }

            if (extras != null)
            {
                extras.PutInt(ActionNotificationIdKey, notifyId);
                extras.PutString(ActionNotificationTagKey, tag);
                resultIntent.PutExtras(extras);
            }

            resultIntent.SetFlags(ActivityFlags.ClearTop);

            var pendingIntent = PendingIntent.GetActivity(context, 0, resultIntent, PendingIntentFlags.OneShot | PendingIntentFlags.UpdateCurrent);

            var notificationBuilder = new NotificationCompat.Builder(context)
                                      .SetSmallIcon(FirebasePushNotificationManager.IconResource)
                                      .SetContentTitle(title)
                                      .SetSound(FirebasePushNotificationManager.SoundUri)
                                      .SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
                                      .SetContentText(message)
                                      .SetAutoCancel(true)
                                      .SetContentIntent(pendingIntent);


            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.JellyBean)
            {
                // Using BigText notification style to support long message
                var style = new NotificationCompat.BigTextStyle();
                style.BigText(message);
                notificationBuilder.SetStyle(style);
            }

            string category = string.Empty;

            if (parameters.ContainsKey(CategoryKey))
            {
                category = parameters[CategoryKey];
            }

            if (parameters.ContainsKey(ActionKey))
            {
                category = parameters[ActionKey];
            }
            var notificationCategories = CrossFirebasePushNotification.Current?.GetUserNotificationCategories();

            if (notificationCategories != null && notificationCategories.Length > 0)
            {
                IntentFilter intentFilter = null;
                foreach (var userCat in notificationCategories)
                {
                    if (userCat != null && userCat.Actions != null && userCat.Actions.Count > 0)
                    {
                        foreach (var action in userCat.Actions)
                        {
                            if (userCat.Category.Equals(category, StringComparison.CurrentCultureIgnoreCase))
                            {
                                Intent        actionIntent        = null;
                                PendingIntent pendingActionIntent = null;


                                if (action.Type == NotificationActionType.Foreground)
                                {
                                    actionIntent = context.PackageManager.GetLaunchIntentForPackage(context.PackageName);
                                    actionIntent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask);
                                    actionIntent.SetAction($"{action.Id}");
                                    extras.PutString(ActionIdentifierKey, action.Id);
                                    actionIntent.PutExtras(extras);
                                    pendingActionIntent = PendingIntent.GetActivity(context, 0, actionIntent, PendingIntentFlags.OneShot | PendingIntentFlags.UpdateCurrent);
                                }
                                else
                                {
                                    actionIntent = new Intent();
                                    //actionIntent.SetAction($"{category}.{action.Id}");
                                    actionIntent.SetAction($"{Application.Context.PackageManager.GetPackageInfo(Application.Context.PackageName, PackageInfoFlags.MetaData).PackageName}.{action.Id}");
                                    extras.PutString(ActionIdentifierKey, action.Id);
                                    actionIntent.PutExtras(extras);
                                    pendingActionIntent = PendingIntent.GetBroadcast(context, 0, actionIntent, PendingIntentFlags.OneShot | PendingIntentFlags.UpdateCurrent);
                                }

                                notificationBuilder.AddAction(context.Resources.GetIdentifier(action.Icon, "drawable", Application.Context.PackageName), action.Title, pendingActionIntent);
                            }


                            if (FirebasePushNotificationManager.ActionReceiver == null)
                            {
                                if (intentFilter == null)
                                {
                                    intentFilter = new IntentFilter();
                                }

                                if (!intentFilter.HasAction(action.Id))
                                {
                                    intentFilter.AddAction($"{Application.Context.PackageManager.GetPackageInfo(Application.Context.PackageName, PackageInfoFlags.MetaData).PackageName}.{action.Id}");
                                }
                            }
                        }
                    }
                }
                if (intentFilter != null)
                {
                    FirebasePushNotificationManager.ActionReceiver = new PushNotificationActionReceiver();
                    context.RegisterReceiver(FirebasePushNotificationManager.ActionReceiver, intentFilter);
                }
            }


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

            notificationManager.Notify(tag, notifyId, notificationBuilder.Build());
        }
        private void CreateNotification(string title, string message, int notifyId, string tag, Bundle extras)
        {
            System.Diagnostics.Debug.WriteLine(
                $"{PushNotificationContants.DomainName} - PushNotification - Message {title} : {message}");

            NotificationCompat.Builder builder = null;
            var context = global::Android.App.Application.Context;

            if (CrossPushNotification.SoundUri == null)
            {
                CrossPushNotification.SoundUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
            }

            try
            {
                if (CrossPushNotification.IconResource == 0)
                {
                    CrossPushNotification.IconResource = context.ApplicationInfo.Icon;
                }
                else
                {
                    var name = context.Resources.GetResourceName(CrossPushNotification.IconResource);
                    if (name == null)
                    {
                        CrossPushNotification.IconResource = context.ApplicationInfo.Icon;
                    }
                }
            }
            catch (global::Android.Content.Res.Resources.NotFoundException ex)
            {
                CrossPushNotification.IconResource = context.ApplicationInfo.Icon;
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }

            var resultIntent = context.PackageManager.GetLaunchIntentForPackage(context.PackageName);

            if (extras != null)
            {
                resultIntent.PutExtras(extras);
            }

            // Create a PendingIntent; we're only using one PendingIntent (ID = 0):
            const int pendingIntentId     = 0;
            var       resultPendingIntent = PendingIntent.GetActivity(context, pendingIntentId,
                                                                      resultIntent, PendingIntentFlags.OneShot);

            // Build the notification
            builder = new NotificationCompat.Builder(context)
                      .SetAutoCancel(true)                              // dismiss the notification from the notification area when the user clicks on it
                      .SetContentIntent(resultPendingIntent)            // start up this activity when the user clicks the intent.
                      .SetContentTitle(title)                           // Set the title
                      .SetSound(CrossPushNotification.SoundUri)
                      .SetSmallIcon(CrossPushNotification.IconResource) // This is the icon to display
                      .SetContentText(message);                         // the message to display.

            if (Build.VERSION.SdkInt >= BuildVersionCodes.JellyBean)
            {
                // Using BigText notification style to support long message
                var style = new NotificationCompat.BigTextStyle();
                style.BigText(message);
                builder.SetStyle(style);
            }

            var notificationManager = (NotificationManager)context.GetSystemService(NotificationService);

            notificationManager.Notify(tag, notifyId, builder.Build());
        }
Ejemplo n.º 36
0
        private void CreateNoti()
        {
            try
            {
                BigViews   = new RemoteViews(PackageName, Resource.Layout.CustomNotificationLayout);
                SmallViews = new RemoteViews(PackageName, Resource.Layout.CustomNotificationSmallLayout);

                Intent notificationIntent = new Intent(this, typeof(SplashScreenActivity));
                notificationIntent.SetAction(Intent.ActionMain);
                notificationIntent.AddCategory(Intent.CategoryLauncher);
                notificationIntent.PutExtra("isnoti", true);
                PendingIntent pendingIntent = PendingIntent.GetActivity(this, 0, notificationIntent, PendingIntentFlags.UpdateCurrent);

                Intent previousIntent = new Intent(this, typeof(PlayerService));
                previousIntent.SetAction(ActionRewind);
                PendingIntent ppreviousIntent = PendingIntent.GetService(this, 0, previousIntent, 0);

                Intent playIntent = new Intent(this, typeof(PlayerService));
                playIntent.SetAction(ActionToggle);
                PendingIntent pplayIntent = PendingIntent.GetService(this, 0, playIntent, 0);

                Intent nextIntent = new Intent(this, typeof(PlayerService));
                nextIntent.SetAction(ActionSkip);
                PendingIntent pnextIntent = PendingIntent.GetService(this, 0, nextIntent, 0);

                Intent closeIntent = new Intent(this, typeof(PlayerService));
                closeIntent.SetAction(ActionStop);
                PendingIntent pcloseIntent = PendingIntent.GetService(this, 0, closeIntent, 0);

                Notification = new NotificationCompat.Builder(this, NotificationChannelId)
                               .SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Mipmap.icon))
                               .SetContentTitle(AppSettings.ApplicationName)
                               .SetPriority((int)NotificationPriority.Max)
                               .SetContentIntent(pendingIntent)
                               .SetSmallIcon(Resource.Drawable.icon_notification)
                               .SetTicker(Constant.ArrayListPlay[Constant.PlayPos]?.Title)
                               .SetChannelId(NotificationChannelId)
                               .SetOngoing(true)
                               .SetAutoCancel(true)
                               .SetOnlyAlertOnce(true);

                NotificationChannel mChannel;
                if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
                {
                    NotificationImportance importance = NotificationImportance.Low;
                    mChannel = new NotificationChannel(NotificationChannelId, AppSettings.ApplicationName, importance);
                    MNotificationManager.CreateNotificationChannel(mChannel);

                    MediaSessionCompat mMediaSession = new MediaSessionCompat(Application.Context, AppSettings.ApplicationName);
                    mMediaSession.SetFlags(MediaSessionCompat.FlagHandlesMediaButtons | MediaSessionCompat.FlagHandlesTransportControls);

                    Notification.SetStyle(new Android.Support.V4.Media.App.NotificationCompat.MediaStyle()
                                          .SetMediaSession(mMediaSession.SessionToken).SetShowCancelButton(true)
                                          .SetShowActionsInCompactView(0, 1, 2)
                                          .SetCancelButtonIntent(MediaButtonReceiver.BuildMediaButtonPendingIntent(Application.Context, PlaybackStateCompat.ActionStop)))
                    .AddAction(new NotificationCompat.Action(Resource.Xml.ic_skip_previous, "Previous", ppreviousIntent))
                    .AddAction(new NotificationCompat.Action(Resource.Xml.ic_pause, "Pause", pplayIntent))
                    .AddAction(new NotificationCompat.Action(Resource.Xml.ic_skip_next, "Next", pnextIntent))
                    .AddAction(new NotificationCompat.Action(Resource.Drawable.ic_action_close, "Close", pcloseIntent));
                }
                else
                {
                    string songName   = Methods.FunString.DecodeString(Constant.ArrayListPlay[Constant.PlayPos]?.Title);
                    string genresName = Methods.FunString.DecodeString(Constant.ArrayListPlay[Constant.PlayPos]?.CategoryName) + " " + Application.Context.Resources.GetString(Resource.String.Lbl_Music);

                    BigViews.SetOnClickPendingIntent(Resource.Id.imageView_noti_play, pplayIntent);
                    BigViews.SetOnClickPendingIntent(Resource.Id.imageView_noti_next, pnextIntent);
                    BigViews.SetOnClickPendingIntent(Resource.Id.imageView_noti_prev, ppreviousIntent);
                    BigViews.SetOnClickPendingIntent(Resource.Id.imageView_noti_close, pcloseIntent);
                    SmallViews.SetOnClickPendingIntent(Resource.Id.status_bar_collapse, pcloseIntent);

                    BigViews.SetImageViewResource(Resource.Id.imageView_noti_play, Android.Resource.Drawable.IcMediaPause);
                    BigViews.SetTextViewText(Resource.Id.textView_noti_name, songName);
                    SmallViews.SetTextViewText(Resource.Id.status_bar_track_name, songName);
                    BigViews.SetTextViewText(Resource.Id.textView_noti_artist, genresName);
                    SmallViews.SetTextViewText(Resource.Id.status_bar_artist_name, genresName);
                    BigViews.SetImageViewResource(Resource.Id.imageView_noti, Resource.Mipmap.icon);
                    SmallViews.SetImageViewResource(Resource.Id.status_bar_album_art, Resource.Mipmap.icon);
                    Notification.SetCustomContentView(SmallViews).SetCustomBigContentView(BigViews);
                }

                ShowNotification();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
        public override void OnCreate()
        {
            base.OnCreate();

            if ((Build.VERSION.SdkInt >= BuildVersionCodes.O))
            {
                NotificationManager notificationManager = null;
                string channel_id = "sample_channel_01";
                if ((notificationManager == null))
                {
                    string channel_name = "Accessory_SDK_Sample";
                    notificationManager = ((NotificationManager)(GetSystemService(Context.NotificationService)));
                    var notiChannel = new NotificationChannel(channel_id, channel_name, NotificationManager.ImportanceLow);
                    notificationManager.CreateNotificationChannel(notiChannel);

                    if (notificationManager.GetNotificationChannel(channel_id) == null)
                    {
                        var channel = new NotificationChannel(
                            channel_id,
                            new Java.Lang.String("Channel"),
                            NotificationImportance.Max
                            );
                        string d = "";
                        if (!string.IsNullOrWhiteSpace(d))
                        {
                            channel.Description = d;
                        }

                        notificationManager.CreateNotificationChannel(channel);
                    }
                }

                int notifyID = 1;

                NotificationCompat.Builder builder = new NotificationCompat.Builder(Application.Context)
                                                     .SetChannelId(channel_id)
                                                     .SetAutoCancel(true)
                                                     .SetContentTitle(TAG)
                                                     .SetContentText("connected to your watch")
                                                     .SetPriority(1)
                                                     .SetVisibility(1)
                                                     .SetCategory(Android.App.Notification.CategoryEvent);
                StartForeground(notifyID, builder.Build());
            }


            _context   = this;
            _isRunning = false;

            var mAccessory = new SA();

            try
            {
                mAccessory.Initialize(this);
            }
            catch (SsdkUnsupportedException)
            {
                // try to handle SsdkUnsupportedException
            }
            catch (Exception e1)
            {
                e1.ToString();

                /*
                 * Your application can not use Samsung Accessory SDK. Your application should work smoothly
                 * without using this SDK, or you may want to notify user and close your application gracefully
                 * (release resources, stop Service threads, close UI thread, etc.)
                 */
                StopSelf();
            }

            bool isFeatureEnabled = mAccessory.IsFeatureEnabled(SA.DeviceAccessory);
        }
Ejemplo n.º 38
0
        public virtual void OnReceived(IDictionary <string, object> parameters)
        {
            System.Diagnostics.Debug.WriteLine($"{DomainTag} - OnReceived");

            if ((parameters.TryGetValue(SilentKey, out var silent) && (silent.ToString() == "true" || silent.ToString() == "1")) || (IsInForeground() && (!(parameters.TryGetValue(PriorityKey, out var imp) && ($"{imp}" == "high" || $"{imp}" == "max")) || (PushNotificationManager.DefaultNotificationChannelImportance != NotificationImportance.High && PushNotificationManager.DefaultNotificationChannelImportance != NotificationImportance.Max))))
            {
                return;
            }

            Context context = Application.Context;

            var notifyId = 0;
            var title    = context.ApplicationInfo.LoadLabel(context.PackageManager);
            var message  = string.Empty;
            var tag      = string.Empty;

            if (!string.IsNullOrEmpty(PushNotificationManager.NotificationContentTextKey) && parameters.TryGetValue(PushNotificationManager.NotificationContentTextKey, out var notificationContentText))
            {
                message = notificationContentText.ToString();
            }
            else if (parameters.TryGetValue(AlertKey, out var alert))
            {
                message = $"{alert}";
            }
            else if (parameters.TryGetValue(BodyKey, out var body))
            {
                message = $"{body}";
            }
            else if (parameters.TryGetValue(MessageKey, out var messageContent))
            {
                message = $"{messageContent}";
            }
            else if (parameters.TryGetValue(SubtitleKey, out var subtitle))
            {
                message = $"{subtitle}";
            }
            else if (parameters.TryGetValue(TextKey, out var text))
            {
                message = $"{text}";
            }

            if (!string.IsNullOrEmpty(PushNotificationManager.NotificationContentTitleKey) && parameters.TryGetValue(PushNotificationManager.NotificationContentTitleKey, out var notificationContentTitle))
            {
                title = notificationContentTitle.ToString();
            }
            else if (parameters.TryGetValue(TitleKey, out var titleContent))
            {
                if (!string.IsNullOrEmpty(message))
                {
                    title = $"{titleContent}";
                }
                else
                {
                    message = $"{titleContent}";
                }
            }

            if (parameters.TryGetValue(IdKey, out var id))
            {
                try
                {
                    notifyId = Convert.ToInt32(id);
                }
                catch (Exception ex)
                {
                    // Keep the default value of zero for the notify_id, but log the conversion problem.
                    System.Diagnostics.Debug.WriteLine($"Failed to convert {id} to an integer {ex}");
                }
            }


            if (parameters.TryGetValue(ShowWhenKey, out var shouldShowWhen) && $"{shouldShowWhen}" == "false")
            {
                PushNotificationManager.ShouldShowWhen = false;
            }

            if (parameters.TryGetValue(TagKey, out var tagContent))
            {
                tag = tagContent.ToString();
            }

            try
            {
                if (parameters.TryGetValue(SoundKey, out var sound))
                {
                    var soundName  = sound.ToString();
                    var soundResId = context.Resources.GetIdentifier(soundName, "raw", context.PackageName);
                    if (soundResId == 0 && soundName.IndexOf('.') != -1)
                    {
                        soundName  = soundName.Substring(0, soundName.LastIndexOf('.'));
                        soundResId = context.Resources.GetIdentifier(soundName, "raw", context.PackageName);
                    }

                    PushNotificationManager.SoundUri = new Android.Net.Uri.Builder()
                                                       .Scheme(ContentResolver.SchemeAndroidResource)
                                                       .Path($"{context.PackageName}/{soundResId}")
                                                       .Build();
                }
            }
            catch (Resources.NotFoundException ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }

            if (PushNotificationManager.SoundUri == null)
            {
                PushNotificationManager.SoundUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
            }
            try
            {
                if (parameters.TryGetValue(IconKey, out var icon) && icon != null)
                {
                    try
                    {
                        PushNotificationManager.IconResource = context.Resources.GetIdentifier(icon.ToString(), "drawable", Application.Context.PackageName);
                    }
                    catch (Resources.NotFoundException ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex.ToString());
                    }
                }

                if (PushNotificationManager.IconResource == 0)
                {
                    PushNotificationManager.IconResource = context.ApplicationInfo.Icon;
                }
                else
                {
                    var name = context.Resources.GetResourceName(PushNotificationManager.IconResource);
                    if (name == null)
                    {
                        PushNotificationManager.IconResource = context.ApplicationInfo.Icon;
                    }
                }
            }
            catch (Resources.NotFoundException ex)
            {
                PushNotificationManager.IconResource = context.ApplicationInfo.Icon;
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }


            try
            {
                if (parameters.TryGetValue(LargeIconKey, out object largeIcon) && largeIcon != null)
                {
                    PushNotificationManager.LargeIconResource = context.Resources.GetIdentifier($"{largeIcon}", "drawable", Application.Context.PackageName);
                    if (PushNotificationManager.LargeIconResource == 0)
                    {
                        PushNotificationManager.LargeIconResource = context.Resources.GetIdentifier($"{largeIcon}", "mipmap", Application.Context.PackageName);
                    }
                }

                if (PushNotificationManager.LargeIconResource > 0)
                {
                    string name = context.Resources.GetResourceName(PushNotificationManager.LargeIconResource);
                    if (name == null)
                    {
                        PushNotificationManager.LargeIconResource = 0;
                    }
                }
            }
            catch (Resources.NotFoundException ex)
            {
                PushNotificationManager.LargeIconResource = 0;
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }

            if (parameters.TryGetValue(ColorKey, out var color) && color != null)
            {
                try
                {
                    PushNotificationManager.Color = Color.ParseColor(color.ToString());
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"{DomainTag} - Failed to parse color {ex}");
                }
            }

            Intent resultIntent = typeof(Activity).IsAssignableFrom(PushNotificationManager.NotificationActivityType) ? new Intent(Application.Context, PushNotificationManager.NotificationActivityType) : (PushNotificationManager.DefaultNotificationActivityType == null ? context.PackageManager.GetLaunchIntentForPackage(context.PackageName) : new Intent(Application.Context, PushNotificationManager.DefaultNotificationActivityType));

            var extras = new Bundle();

            foreach (var p in parameters)
            {
                extras.PutString(p.Key, p.Value.ToString());
            }

            if (extras != null)
            {
                extras.PutInt(ActionNotificationIdKey, notifyId);
                extras.PutString(ActionNotificationTagKey, tag);
                resultIntent.PutExtras(extras);
            }

            if (PushNotificationManager.NotificationActivityFlags != null)
            {
                resultIntent.SetFlags(PushNotificationManager.NotificationActivityFlags.Value);
            }
            var requestCode   = new Java.Util.Random().NextInt();
            var pendingIntent = PendingIntent.GetActivity(context, requestCode, resultIntent, PendingIntentFlags.UpdateCurrent);


            var chanId = PushNotificationManager.DefaultNotificationChannelId;

            if (parameters.TryGetValue(ChannelIdKey, out var channelId) && channelId != null)
            {
                chanId = $"{channelId}";
            }

            var notificationBuilder = new NotificationCompat.Builder(context, chanId)
                                      .SetSmallIcon(PushNotificationManager.IconResource)
                                      .SetContentTitle(title)
                                      .SetContentText(message)
                                      .SetAutoCancel(true)
                                      .SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis())
                                      .SetContentIntent(pendingIntent);

            if (Build.VERSION.SdkInt >= BuildVersionCodes.JellyBeanMr1)
            {
                notificationBuilder.SetShowWhen(PushNotificationManager.ShouldShowWhen);
            }

            if (PushNotificationManager.LargeIconResource > 0)
            {
                Bitmap largeIconBitmap = BitmapFactory.DecodeResource(context.Resources, PushNotificationManager.LargeIconResource);
                notificationBuilder.SetLargeIcon(largeIconBitmap);
            }

            if (parameters.TryGetValue(FullScreenIntentKey, out var fullScreenIntent) && ($"{fullScreenIntent}" == "true" || $"{fullScreenIntent}" == "1"))
            {
                var fullScreenPendingIntent = PendingIntent.GetActivity(context, requestCode, resultIntent, PendingIntentFlags.UpdateCurrent);
                notificationBuilder.SetFullScreenIntent(fullScreenPendingIntent, true);
                notificationBuilder.SetCategory(NotificationCompat.CategoryCall);
                parameters[PriorityKey] = "high";
            }

            var deleteIntent        = new Intent(context, typeof(PushNotificationDeletedReceiver));
            var pendingDeleteIntent = PendingIntent.GetBroadcast(context, requestCode, deleteIntent, PendingIntentFlags.UpdateCurrent);

            notificationBuilder.SetDeleteIntent(pendingDeleteIntent);

            if (Build.VERSION.SdkInt < BuildVersionCodes.O)
            {
                if (parameters.TryGetValue(PriorityKey, out var priority) && priority != null)
                {
                    var priorityValue = $"{priority}";
                    if (!string.IsNullOrEmpty(priorityValue))
                    {
                        switch (priorityValue.ToLower())
                        {
                        case "max":
                            notificationBuilder.SetPriority(NotificationCompat.PriorityMax);
                            notificationBuilder.SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
                            break;

                        case "high":
                            notificationBuilder.SetPriority(NotificationCompat.PriorityHigh);
                            notificationBuilder.SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
                            break;

                        case "default":
                            notificationBuilder.SetPriority(NotificationCompat.PriorityDefault);
                            notificationBuilder.SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
                            break;

                        case "low":
                            notificationBuilder.SetPriority(NotificationCompat.PriorityLow);
                            break;

                        case "min":
                            notificationBuilder.SetPriority(NotificationCompat.PriorityMin);
                            break;

                        default:
                            notificationBuilder.SetPriority(NotificationCompat.PriorityDefault);
                            notificationBuilder.SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
                            break;
                        }
                    }
                    else
                    {
                        notificationBuilder.SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
                    }
                }
                else
                {
                    notificationBuilder.SetVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
                }

                try
                {
                    notificationBuilder.SetSound(PushNotificationManager.SoundUri);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"{DomainTag} - Failed to set sound {ex}");
                }
            }

            // Try to resolve (and apply) localized parameters
            ResolveLocalizedParameters(notificationBuilder, parameters);

            if (PushNotificationManager.Color != null)
            {
                notificationBuilder.SetColor(PushNotificationManager.Color.Value);
            }

            if (Build.VERSION.SdkInt >= BuildVersionCodes.JellyBean)
            {
                // Using BigText notification style to support long message
                var style = new NotificationCompat.BigTextStyle();
                style.BigText(message);
                notificationBuilder.SetStyle(style);
            }

            var category = string.Empty;

            if (parameters.TryGetValue(CategoryKey, out var categoryContent))
            {
                category = categoryContent.ToString();
            }

            if (parameters.TryGetValue(ActionKey, out var actionContent))
            {
                category = actionContent.ToString();
            }

            var notificationCategories = CrossPushNotification.Current?.GetUserNotificationCategories();

            if (notificationCategories != null && notificationCategories.Length > 0)
            {
                foreach (var userCat in notificationCategories)
                {
                    if (userCat != null && userCat.Actions != null && userCat.Actions.Count > 0)
                    {
                        foreach (var action in userCat.Actions)
                        {
                            var aRequestCode = Guid.NewGuid().GetHashCode();
                            if (userCat.Category.Equals(category, StringComparison.CurrentCultureIgnoreCase))
                            {
                                Intent        actionIntent        = null;
                                PendingIntent pendingActionIntent = null;

                                if (action.Type == NotificationActionType.Foreground)
                                {
                                    actionIntent = typeof(Activity).IsAssignableFrom(PushNotificationManager.NotificationActivityType) ? new Intent(Application.Context, PushNotificationManager.NotificationActivityType) : (PushNotificationManager.DefaultNotificationActivityType == null ? context.PackageManager.GetLaunchIntentForPackage(context.PackageName) : new Intent(Application.Context, PushNotificationManager.DefaultNotificationActivityType));

                                    if (PushNotificationManager.NotificationActivityFlags != null)
                                    {
                                        actionIntent.SetFlags(PushNotificationManager.NotificationActivityFlags.Value);
                                    }

                                    extras.PutString(ActionIdentifierKey, action.Id);
                                    actionIntent.PutExtras(extras);
                                    pendingActionIntent = PendingIntent.GetActivity(context, aRequestCode, actionIntent, PendingIntentFlags.UpdateCurrent);
                                }
                                else
                                {
                                    actionIntent = new Intent(context, typeof(PushNotificationActionReceiver));
                                    extras.PutString(ActionIdentifierKey, action.Id);
                                    actionIntent.PutExtras(extras);
                                    pendingActionIntent = PendingIntent.GetBroadcast(context, aRequestCode, actionIntent, PendingIntentFlags.UpdateCurrent);
                                }

                                notificationBuilder.AddAction(context.Resources.GetIdentifier(action.Icon, "drawable", Application.Context.PackageName), action.Title, pendingActionIntent);
                            }
                        }
                    }
                }
            }

            OnBuildNotification(notificationBuilder, parameters);

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

            notificationManager.Notify(tag, notifyId, notificationBuilder.Build());
        }
Ejemplo n.º 39
0
 /// <summary>
 /// Override to provide customization of the notification to build.
 /// </summary>
 /// <param name="notificationBuilder">Notification builder.</param>
 /// <param name="parameters">Notification parameters.</param>
 public virtual void OnBuildNotification(NotificationCompat.Builder notificationBuilder, IDictionary <string, object> parameters)
 {
 }
        /// <summary>
        /// Create local notification
        /// </summary>
        /// <param name="title"></param>
        /// <param name="message"></param>
        public void CreateNotification(string title, string message)
        {
            try
            {
                NotificationCompat.Builder builder = null;
                Context context = Android.App.Application.Context;

                if (CrossGeofence.SoundUri == null)
                {
                    CrossGeofence.SoundUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
                }
                try
                {
                    if (CrossGeofence.IconResource == 0)
                    {
                        CrossGeofence.IconResource = context.ApplicationInfo.Icon;
                    }
                    else
                    {
                        string name = context.Resources.GetResourceName(CrossGeofence.IconResource);

                        if (name == null)
                        {
                            CrossGeofence.IconResource = context.ApplicationInfo.Icon;
                        }
                    }
                }
                catch (Android.Content.Res.Resources.NotFoundException ex)
                {
                    CrossGeofence.IconResource = context.ApplicationInfo.Icon;
                    System.Diagnostics.Debug.WriteLine(ex.ToString());
                }

                Intent resultIntent = context.PackageManager.GetLaunchIntentForPackage(context.PackageName);

                // Create a PendingIntent; we're only using one PendingIntent (ID = 0):
                const int     pendingIntentId     = 0;
                PendingIntent resultPendingIntent = PendingIntent.GetActivity(context, pendingIntentId, resultIntent, PendingIntentFlags.OneShot);


                // Build the notification
                builder = new NotificationCompat.Builder(context)
                          .SetAutoCancel(true)                      // dismiss the notification from the notification area when the user clicks on it
                          .SetContentIntent(resultPendingIntent)    // start up this activity when the user clicks the intent.
                          .SetContentTitle(title)                   // Set the title
                          .SetSound(CrossGeofence.SoundUri)
                          .SetSmallIcon(CrossGeofence.IconResource) // This is the icon to display
                          .SetContentText(message);                 // the message to display.

                // Set the icon resource if we have one
                if (CrossGeofence.LargeIconResource != null)
                {
                    builder.SetLargeIcon(CrossGeofence.LargeIconResource);
                }

                // Set the color if we have one
                if (CrossGeofence.Color != 0)
                {
                    builder.SetColor(CrossGeofence.Color);
                }


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

                if (NotificationId >= NotificationMaxId)
                {
                    NotificationId = 0;
                }

                notificationManager.Notify(NotificationId++, builder.Build());
            }
            catch (Java.Lang.Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(string.Format("{0} - {1}", CrossGeofence.Id, ex.ToString()));
            }
            catch (System.Exception ex1)
            {
                System.Diagnostics.Debug.WriteLine(string.Format("{0} - {1}", CrossGeofence.Id, ex1.ToString()));
            }
        }
Ejemplo n.º 41
0
        public Notification CreateNotification(NotificationViewModel notificationViewModel)
        {
            string channelId;
            int    notificationPriority;

            switch (notificationViewModel.Type)
            {
            case NotificationsEnum.NewMessageReceived:
                channelId            = _exposureChannelId;
                notificationPriority = NotificationCompat.PriorityHigh;
                break;

            case NotificationsEnum.BackgroundFetch:
                channelId            = _backgroundFetchChannelId;
                notificationPriority = NotificationCompat.PriorityLow;
                break;

            default:
                channelId            = _permissionsChannelId;
                notificationPriority = NotificationCompat.PriorityHigh;
                break;
            }

            PendingIntent resultPendingIntent = InitResultIntentBasingOnViewModel(notificationViewModel);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(NotificationContext, channelId)
                                                 .SetAutoCancel(true)                          // Dismiss the notification from the notification area when the user clicks on it
                                                 .SetContentTitle(notificationViewModel.Title) // Set the title
                                                 .SetContentText(notificationViewModel.Body)   // the message to display.
                                                 .SetContentIntent(resultPendingIntent)        // Start up this activity when the user clicks the intent.
                                                 .SetVibrate(null)
                                                 .SetSound(null)
                                                 .SetNumber(1)
                                                 .SetCategory(NotificationCompat.CategoryMessage)
                                                 .SetOnlyAlertOnce(true)
                                                 .SetPriority(notificationPriority);

            // This is the icon to display
            if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
            {
                builder.SetColor(Resource.Color.colorPrimary);
            }

            builder.SetSmallIcon(Resource.Drawable.ic_notification);

            Notification notification = builder.Build();

            bool isLowerVersion          = Build.VERSION.SdkInt < BuildVersionCodes.O;
            bool isBadgeCounterSupported = ShortcutBadger.IsBadgeCounterSupported(NotificationContext);
            bool isMessage = notificationViewModel.Type == NotificationsEnum.NewMessageReceived;
            bool areNotificationsEnabled = NotificationManagerCompat.From(NotificationContext).AreNotificationsEnabled();

            // Use Plugin for badges on older platforms that support them
            if (isLowerVersion &&
                isBadgeCounterSupported &&
                isMessage &&
                areNotificationsEnabled)
            {
                ShortcutBadger.ApplyNotification(NotificationContext, notification, 1);
            }

            return(notification);
        }
Ejemplo n.º 42
0
        public void CreateNotification(String title, String message)
        {
            try
            {
                var intent = new Intent(mContext, typeof(MainActivity));
                intent.AddFlags(ActivityFlags.ClearTop);
                intent.PutExtra(title, message);
                var pendingIntent = PendingIntent.GetActivity(mContext, 0, intent, PendingIntentFlags.OneShot);

                var sound = global::Android.Net.Uri.Parse(ContentResolver.SchemeAndroidResource + "://" + mContext.PackageName + "/" + Resource.Raw.ringtone);
                // Creating an Audio Attribute
                alarmAttributes = new AudioAttributes.Builder()
                                  .SetContentType(AudioContentType.Sonification)
                                  .SetUsage(AudioUsageKind.Notification).Build();

                mBuilder = new NotificationCompat.Builder(mContext);
                mBuilder.SetSmallIcon(Resource.Drawable.onlylogo);
                mBuilder.SetContentTitle(title)
                .SetSound(sound)
                .SetAutoCancel(false)
                .SetTimeoutAfter(25000)
                .SetContentTitle(title)
                .SetContentText(message)
                .SetChannelId(NOTIFICATION_CHANNEL_ID)
                .SetPriority(( int )NotificationPriority.High)
                .SetVibrate(new long [2])
                .SetDefaults(( int )NotificationDefaults.Sound | ( int )NotificationDefaults.Vibrate)
                .SetVisibility(( int )NotificationVisibility.Public)
                .SetColor(80)
                .SetVisibility(50)
                .SetContentIntent(pendingIntent);



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

                if (global::Android.OS.Build.VERSION.SdkInt >= global::Android.OS.BuildVersionCodes.O)
                {
                    NotificationImportance importance = global::Android.App.NotificationImportance.High;

                    NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, title, importance);
                    notificationChannel.EnableLights(true);
                    notificationChannel.EnableVibration(true);
                    notificationChannel.SetSound(sound, alarmAttributes);
                    notificationChannel.SetShowBadge(true);
                    notificationChannel.Importance = NotificationImportance.High;
                    notificationChannel.SetVibrationPattern(new long [] { 100, 200, 300, 400, 500, 400, 300, 200, 400 });

                    if (notificationManager != null)
                    {
                        mBuilder.SetChannelId(NOTIFICATION_CHANNEL_ID);
                        notificationManager.CreateNotificationChannel(notificationChannel);
                    }
                }

                notificationManager.Notify(0, mBuilder.Build());
            }
            catch (Exception ex)
            {
                //
            }
        }
Ejemplo n.º 43
0
        private void ShowNow(NotificationRequest request)
        {
            Cancel(request.NotificationId);

            if (string.IsNullOrWhiteSpace(request.Android.ChannelId))
            {
                request.Android.ChannelId = NotificationCenter.DefaultChannelId;
            }

            using var builder = new NotificationCompat.Builder(Application.Context, request.Android.ChannelId);
            builder.SetContentTitle(request.Title);
            builder.SetContentText(request.Description);
            using (var bigTextStyle = new NotificationCompat.BigTextStyle())
            {
                var bigText = bigTextStyle.BigText(request.Description);
                builder.SetStyle(bigText);
            }
            builder.SetNumber(request.BadgeNumber);
            builder.SetAutoCancel(request.Android.AutoCancel);
            builder.SetOngoing(request.Android.Ongoing);

            if (string.IsNullOrWhiteSpace(request.Android.Group) == false)
            {
                builder.SetGroup(request.Android.Group);
                if (request.Android.IsGroupSummary)
                {
                    builder.SetGroupSummary(true);
                }
            }

            if (Build.VERSION.SdkInt < BuildVersionCodes.O)
            {
                builder.SetPriority((int)request.Android.Priority);

                var soundUri = NotificationCenter.GetSoundUri(request.Sound);
                if (soundUri != null)
                {
                    builder.SetSound(soundUri);
                }
            }

            if (request.Android.VibrationPattern != null)
            {
                builder.SetVibrate(request.Android.VibrationPattern);
            }

            if (request.Android.ProgressBarMax.HasValue &&
                request.Android.ProgressBarProgress.HasValue &&
                request.Android.ProgressBarIndeterminate.HasValue)
            {
                builder.SetProgress(request.Android.ProgressBarMax.Value,
                                    request.Android.ProgressBarProgress.Value,
                                    request.Android.ProgressBarIndeterminate.Value);
            }

            if (request.Android.Color.HasValue)
            {
                builder.SetColor(request.Android.Color.Value);
            }

            builder.SetSmallIcon(GetIcon(request.Android.IconName));
            if (request.Android.TimeoutAfter.HasValue)
            {
                builder.SetTimeoutAfter((long)request.Android.TimeoutAfter.Value.TotalMilliseconds);
            }

            var notificationIntent = Application.Context.PackageManager.GetLaunchIntentForPackage(Application.Context.PackageName);

            notificationIntent.SetFlags(ActivityFlags.SingleTop);
            notificationIntent.PutExtra(NotificationCenter.ExtraReturnDataAndroid, request.ReturningData);
            var pendingIntent = PendingIntent.GetActivity(Application.Context, request.NotificationId, notificationIntent,
                                                          PendingIntentFlags.CancelCurrent);

            builder.SetContentIntent(pendingIntent);

            var notification = builder.Build();

            if (Build.VERSION.SdkInt < BuildVersionCodes.O &&
                request.Android.LedColor.HasValue)
            {
                notification.LedARGB = request.Android.LedColor.Value;
            }

            if (Build.VERSION.SdkInt < BuildVersionCodes.O &&
                string.IsNullOrWhiteSpace(request.Sound))
            {
                notification.Defaults = NotificationDefaults.All;
            }
            _notificationManager?.Notify(request.NotificationId, notification);
        }
Ejemplo n.º 44
0
 protected abstract NotificationCompat.Builder ConfigureNotificationBuilder(Context context, TNotificationData notificationData, NotificationCompat.Builder notificationBuilder);
Ejemplo n.º 45
0
        //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)
                          .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());
            }
        }
Ejemplo n.º 46
0
        private void StartNotification()
        {
            Intent playintent = new Intent(AndroidApp.Context, typeof(Receiver));

            playintent.PutExtra(ResourceName, "playButton");

            Intent beforeintent = new Intent(AndroidApp.Context, typeof(Receiver));

            beforeintent.PutExtra(ResourceName, "beforeButton");

            Intent nextIntent = new Intent(AndroidApp.Context, typeof(Receiver));

            nextIntent.PutExtra(ResourceName, "nextButton");

            Intent closeIntent = new Intent(AndroidApp.Context, typeof(Receiver));

            closeIntent.PutExtra(ResourceName, "closeButton");

            Intent titleIntent = new Intent(AndroidApp.Context, typeof(MainActivity));

            titleIntent.PutExtra(ResourceName, "contentTitle");

            PendingIntent playPendingIntent   = PendingIntent.GetBroadcast(AndroidApp.Context, 1, playintent, PendingIntentFlags.UpdateCurrent);
            PendingIntent beforePendingIntent = PendingIntent.GetBroadcast(AndroidApp.Context, 2, beforeintent, PendingIntentFlags.UpdateCurrent);
            PendingIntent nextPendingIntent   = PendingIntent.GetBroadcast(AndroidApp.Context, 3, nextIntent, PendingIntentFlags.UpdateCurrent);
            PendingIntent closePendingIntent  = PendingIntent.GetBroadcast(AndroidApp.Context, 4, closeIntent, PendingIntentFlags.UpdateCurrent);
            PendingIntent titlePendingIntent  = PendingIntent.GetActivity(AndroidApp.Context, 5, titleIntent, PendingIntentFlags.UpdateCurrent);


            NotificationCompat.Builder builder = new NotificationCompat.Builder(AndroidApp.Context, channelId)
                                                 .SetContentText(NowPlay.Title)
                                                 .SetLargeIcon(ThumbnailUtils.CreateVideoThumbnail(NowPlay.path, ThumbnailKind.MiniKind))
                                                 .SetSmallIcon(Resource.Drawable.icon)
                                                 .SetContentIntent(titlePendingIntent)
                                                 .SetShowWhen(false)
                                                 .SetAutoCancel(true)
                                                 .AddAction(Resource.Drawable.prev_mini, "", beforePendingIntent);

            if (NowPlay.Audio.IsPlaying)
            {
                builder.AddAction(Resource.Drawable.pause_mini, "", playPendingIntent);
            }

            else
            {
                builder.AddAction(Resource.Drawable.play_mini, "", playPendingIntent);
            }

            builder.AddAction(Resource.Drawable.next_mini, "", nextPendingIntent)
            .AddAction(Resource.Drawable.close_mini, "", closePendingIntent)
            .SetStyle(new MediaStyle()
                      .SetShowActionsInCompactView(0, 1, 2));

            var notification = builder.Build();

            notification.Flags = NotificationFlags.NoClear;

            var manager = (Android.App.NotificationManager)AndroidApp.Context.GetSystemService(AndroidApp.NotificationService);

            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                var channelNameJava = new Java.Lang.String(channelName);
                var channel         = new NotificationChannel(channelId, channelNameJava, NotificationImportance.Default)
                {
                    Description = channelDescription
                };

                channel.SetSound(null, null);
                channel.SetVibrationPattern(new long[] { 0 });
                channel.EnableVibration(true);
                manager.CreateNotificationChannel(channel);
            }

            StartForeground(serviceNotifID, notification);
        }
Ejemplo n.º 47
0
        public static void StartinCommingCall(Intent Intent, string ImageProfile, string Title, string Long_Description,
                                              int Notification_id)
        {
            try
            {
                notifyMgr = (NotificationManager)Application.Context.GetSystemService(Context.NotificationService);

                if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
                {
                    // Create the NotificationChannel, but only on API 26+ because
                    // the NotificationChannel class is new and not in the support library
                    var channel = new NotificationChannel(CHANNEL_ID, "Message_Notifciation_Channel_1", NotificationImportance.Default); //high
                    var sound   = Android.Net.Uri.Parse("android.resource://" + Application.Context.PackageName + "/raw/mystic_call");

                    AudioAttributes attributes = new AudioAttributes.Builder()
                                                 .SetUsage(AudioUsageKind.Notification)
                                                 .Build();
                    // Configure the notification channel.
                    channel.EnableLights(true);
                    channel.SetSound(sound, attributes); // This is IMPORTANT

                    channel.Description = Application.Context.GetText(Resource.String.Lbl_Notification_of_Messages);
                    channel.EnableVibration(true);
                    channel.LockscreenVisibility = NotificationVisibility.Public;

                    notifyMgr?.CreateNotificationChannel(channel);
                }

                var data_CALL_ID = Intent.GetStringExtra("CallID") ?? "Data not available";
                if (data_CALL_ID != "Data not available" && !String.IsNullOrEmpty(data_CALL_ID))
                {
                    CallID = data_CALL_ID;

                    UserID         = Intent.GetStringExtra("UserID");
                    avatar         = Intent.GetStringExtra("avatar");
                    name           = Intent.GetStringExtra("name");
                    access_token   = Intent.GetStringExtra("access_token");
                    access_token_2 = Intent.GetStringExtra("access_token_2");
                    from_id        = Intent.GetStringExtra("from_id");
                    active         = Intent.GetStringExtra("active");
                    time           = Intent.GetStringExtra("time");
                    status         = Intent.GetStringExtra("status");
                    room_name      = Intent.GetStringExtra("room_name");
                    type           = Intent.GetStringExtra("type");
                    Declined       = Intent.GetStringExtra("declined");
                }

                var NotificationBroadcasterAction =
                    new Intent(Application.Context, typeof(NotificationBroadcasterCloser));
                NotificationBroadcasterAction.PutExtra(NOTIFICATION_ID, Notification_id);
                NotificationBroadcasterAction.PutExtra("type", type);
                NotificationBroadcasterAction.PutExtra("CallID", CallID);
                NotificationBroadcasterAction.PutExtra("action", "dismiss");

                PendingIntent GetAnswerIntent =
                    NotificationManagerClass.NotificationActivity.GetAnswerIntent(Notification_id, Application.Context,
                                                                                  Intent);
                PendingIntent MainIntent = PendingIntent.GetActivity(Application.Context, Notification_id,
                                                                     new Intent(Application.Context, typeof(Tabbed_Main_Page)), 0);
                PendingIntent cancelIntent = PendingIntent.GetBroadcast(Application.Context, Notification_id,
                                                                        NotificationBroadcasterAction, 0);

                NotificationCompat.Builder builder = new NotificationCompat.Builder(Application.Context);

                if (!String.IsNullOrEmpty(ImageProfile))
                {
                    var Image = GetBitmapFromPath(ImageProfile);
                    builder.SetLargeIcon(Image);
                }

                if ((int)Android.OS.Build.VERSION.SdkInt >= 21)
                {
                    builder.SetCategory(Notification.CategoryCall).SetVisibility(NotificationCompat.VisibilityPublic);
                }

                var uri = Android.Net.Uri.Parse("android.resource://" + Application.Context.PackageName + "/raw/mystic_call");

                var Vibrate = new long[]
                {
                    1000, 1000, 2000, 1000, 2000, 1000, 2000, 1000, 2000, 1000, 2000, 1000, 2000, 1000, 2000, 1000,
                    2000, 1000, 2000, 1000, 2000, 1000, 2000, 1000, 2000
                };
                builder.SetPriority(NotificationCompat.PriorityMax);
                builder.SetColorized(true);
                builder.SetColor(Color.ParseColor(AppSettings.MainColor)).SetDeleteIntent(cancelIntent);
                builder.SetSmallIcon(Resource.Drawable.icon)
                .SetContentTitle(Title).SetAutoCancel(true)
                .SetContentText(Long_Description)
                .SetChannelId(CHANNEL_ID)
                .SetContentIntent(cancelIntent).SetLights(Color.Red, 3000, 3000)
                .SetSound(uri)
                .SetOngoing(true).SetVibrate(Vibrate)
                .SetFullScreenIntent(MainIntent, true)
                .AddAction(Resource.Drawable.ic_close_black_24dp, Application.Context.GetText(Resource.String.Lbl_Dismiss), cancelIntent)
                .AddAction(Resource.Drawable.ic_action_notifcation_phone, Application.Context.GetText(Resource.String.Lbl_Answer), GetAnswerIntent);

                Notification NotificationBuild = builder.Build();
                NotificationBuild.Color     = Color.ParseColor(AppSettings.MainColor);
                NotificationBuild.Flags    |= NotificationFlags.Insistent;
                NotificationBuild.Sound     = uri;
                NotificationBuild.Vibrate   = Vibrate;
                builder.Notification.Flags |= NotificationFlags.AutoCancel;


                if (Declined == "0")
                {
                    notifyMgr.Notify(0, NotificationBuild);
                }
                else
                {
                    Application.Context.SendBroadcast(NotificationBroadcasterAction); //Close all incomming calls
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Ejemplo n.º 48
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            // TODO planned features:
            // - History in main activity
            // - Configure download location
            // - Configure download type (support all types available)
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            SetContentView(Resource.Layout.activity_main);

            Android.Support.V7.Widget.Toolbar toolbar = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
            SetSupportActionBar(toolbar);

            EnsurePermissions();

            if (Intent?.Extras != null)
            {
                string youtubeUrl     = Intent.GetStringExtra(Intent.ExtraText);
                int    notificationID = s_NextNotificationID++;

                // Don't run this on the main thread
                Task.Run(async() => {
                    try {
                        var manager = this.GetSystemService <NotificationManager>();

                        var notifBuilder = new NotificationCompat.Builder(ApplicationContext, "youtubedl.download")
                                           .SetSmallIcon(Resource.Mipmap.ic_launcher)
                                           .SetContentText("@string/notif_pre_start")
                                           .SetProgress(100, 0, true);

                        manager.Notify(notificationID, notifBuilder.Build());

                        VideoDownloadService.Connection connection = new VideoDownloadService.Connection();
                        Intent serviceIntent = new Intent(ApplicationContext, typeof(VideoDownloadService));
                        StartService(serviceIntent);
                        bool bindResult = BindService(serviceIntent, connection, Bind.AutoCreate);

                        await Task.Delay(500);
                        DownloadResult result = await connection.Binder.Service.DownloadVideo(youtubeUrl, new Progress <double>(p => {
                            notifBuilder.SetProgress(100, (int)(p * 100), false);
                            manager.Notify(notificationID, notifBuilder.SetOngoing(true).Build());
                        }));

                        UnbindService(connection);
                        //StopService(serviceIntent); // ?

                        manager.Notify(
                            notificationID,
                            new NotificationCompat.Builder(ApplicationContext, result.NotificationChannel)
                            .SetSmallIcon(Resource.Mipmap.ic_launcher)
                            .SetContentTitle(result.VideoTitle ?? result.Video.Value)
                            .SetOngoing(false)
                            .SetContentText(result.Message)
                            .Build()
                            );
                    } catch (Exception e) {
                        Log.Error(Util.LogTag, e.ToStringDemystified());
                    }
                });
                //Finish();
            }
        }
Ejemplo n.º 49
0
        // from https://xamarinhelp.com/xamarin-background-tasks/
        public override async void OnReceive(Context context, Intent intent)
        {
            //PowerManager pm = (PowerManager)context.GetSystemService(Context.PowerService);
            //PowerManager.WakeLock wakeLock = pm.NewWakeLock(WakeLockFlags.Partial, "BackgroundReceiver");

            ////wakeLock.Acquire();


            //var alarmIntent = new Intent(context, typeof(BackgroundReceiver));

            //var pending = PendingIntent.GetBroadcast(context, 0, alarmIntent, PendingIntentFlags.UpdateCurrent);

            //var alarmManager = (AlarmManager)Android.App.Application.Context.GetSystemService(Context.AlarmService);
            //alarmManager.SetExactAndAllowWhileIdle(AlarmType.ElapsedRealtime, SystemClock.ElapsedRealtime() + 1 * 1000, pending);

            ////MessagingCenter.Send<object, string>(this, "UpdateLabel", "Hello from Android");
            //MessagingCenter.Send<object>(this, "SendNotification");


            /////



            //Intent alarmIntent = new Intent(Application.Context, typeof(AlarmReceiver));
            //alarmIntent.PutExtra("message", message);
            //alarmIntent.PutExtra("title", title);

            //// specify the broadcast receiver
            //PendingIntent pendingIntent = PendingIntent.GetBroadcast(Application.Context, 0, alarmIntent, PendingIntentFlags.UpdateCurrent);
            //AlarmManager alarmManager = (AlarmManager)Application.Context.GetSystemService(Context.AlarmService);

            //// set the time when app is woken up
            //// todo: this is where time is adjusted
            //alarmManager.SetInexactRepeating(AlarmType.ElapsedRealtimeWakeup, SystemClock.ElapsedRealtime() + 5 * 1000, 1000, pendingIntent);


            _sqLiteConnection = await Xamarin.Forms.DependencyService.Get <ISQLite>().GetConnection();

            var listDataPower = _sqLiteConnection.Table <Power>().ToList();

            iteratedIndex++;

            //title = listDataPower[iteratedIndex].Title;
            //message = listDataPower[iteratedIndex].Description;



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


            var notIntent     = new Intent(context, typeof(MainActivity));
            var contentIntent = PendingIntent.GetActivity(context, 0, notIntent, PendingIntentFlags.CancelCurrent);
            var manager       = NotificationManagerCompat.From(context);

            var style = new NotificationCompat.BigTextStyle();

            style.BigText(message);

            // sets notifcation logo
            int resourceId;

            resourceId = Resource.Drawable.xamarin_logo;

            var wearableExtender = new NotificationCompat.WearableExtender().SetBackground(BitmapFactory.DecodeResource(context.Resources, resourceId));



            // Generate a notification
            // todo look at notification compat properties
            var builder = new NotificationCompat.Builder(context, channelId)
                          .SetContentIntent(contentIntent)
                          .SetSmallIcon(Resource.Drawable.notification_template_icon_bg)
                          .SetContentTitle(title)
                          .SetContentText(message)
                          .SetStyle(style)
                          .SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis())
                          .SetAutoCancel(true)
                          .Extend(wearableExtender);


            var resultIntent = NotificationService.GetLauncherActivity();

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

            stackBuilder.AddNextIntent(resultIntent);
            Random random       = new Random();
            int    randomNumber = random.Next(9999 - 1000) + 1000;

            var resultPendingIntent =
                stackBuilder.GetPendingIntent(randomNumber, (int)PendingIntentFlags.Immutable);

            builder.SetContentIntent(resultPendingIntent);
            // Sending notification
            var notificationManager = NotificationManagerCompat.From(Application.Context);

            notificationManager.Notify(randomNumber, builder.Build());

            //var notification = builder.Build();
            //manager.Notify(0, notification);

            /////////////////////////////////////////////////////////
            ///

            //wakeLock.Release();

            //////////////////////////////////////////////////////////////////////
        }
Ejemplo n.º 50
0
        public override async void OnReceive(Context context, Intent intent)
        {
            try
            {
                ResourceLocator.RegisterAppDataServiceAdapter(new ApplicationDataServiceService());
                ResourceLocator.RegisterBase();
            }
            catch (Exception)
            {
                //may be already registered... voodoo I guess
            }
            var items        = ResourceLocator.HandyDataStorage.RegisteredAiringNotifications;
            var expiredItems = new List <AiringShowNotificationEntry>();
            await ResourceLocator.AiringInfoProvider.Init(false);

            bool updated             = false;
            var  notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService);

            foreach (var entry in items.StoredItems)
            {
                var intId = int.Parse(entry.Id);
                if (!ResourceLocator.AiringInfoProvider.TryGetCurrentEpisode(intId, out var notificationToTrigger,
                                                                             DateTime.Today))
                {
                    expiredItems.Add(entry);
                    continue;
                }
                if (notificationToTrigger == entry.TriggeredNotifications)
                {
                    continue;
                }

                var notificationIntent = new Intent(context, typeof(MainActivity));
                notificationIntent.SetAction(DateTime.Now.Ticks.ToString());
                notificationIntent.PutExtra("launchArgs", $"https://myanimelist.net/anime/{entry.Id}");
                var pendingIntent =
                    PendingIntent.GetActivity(context, 0, notificationIntent, PendingIntentFlags.OneShot);
                var notificationBuilder = new NotificationCompat.Builder(context)
                                          .SetSmallIcon(Resource.Drawable.ic_stat_name)
                                          .SetContentTitle("New anime episode is on air!")
                                          .SetContentText($"Episode {notificationToTrigger} of {entry.Title} has just aired!")
                                          .SetAutoCancel(true)
                                          .SetGroup("airing")
                                          .SetContentIntent(pendingIntent)
                                          .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification));

                try
                {
                    notificationBuilder.SetLargeIcon(
                        (await ImageService.Instance.LoadUrl(entry.ImageUrl).AsBitmapDrawableAsync()).Bitmap);
                }
                catch (Exception e)
                {
                    //no image
                }


                entry.TriggeredNotifications = notificationToTrigger;
                if (entry.EpisodeCount == entry.TriggeredNotifications)
                {
                    expiredItems.Add(entry);
                }
                else
                {
                    if (!ResourceLocator.AiringInfoProvider.TryGetNextAirDate(intId,
                                                                              DateTime.Today.Add(TimeSpan.FromDays(.9)), out var nextAir))
                    {
                        expiredItems.Add(entry);
                    }
                }

                notificationManager.Notify($"{entry.Id};ep{notificationToTrigger}".GetHashCode(),
                                           notificationBuilder.Build());
                updated = true;
            }


            items.StartBatch();
            foreach (var expiredItem in expiredItems)
            {
                items.StoredItems.Remove(expiredItem);
            }
            items.CommitBatch();

            if (updated)
            {
                ResourceLocator.HandyDataStorage.RegisteredAiringNotifications.SaveData();
            }
        }
 public NotificationCompat.Builder Extend(NotificationCompat.Builder builder)
 {
     return(builder);
 }
 NotificationCompat.Builder LL_OnLocalyticsWillShowPlacesPushNotification(NotificationCompat.Builder builder, PlacesCampaign campaign)
 {
     Console.WriteLine("Will show places push notification. Name: " + campaign.Name + ". Campaign Id: " + campaign.CampaignId + ". Message: " + campaign.Message);
     return(builder);
 }
Ejemplo n.º 53
0
        public static void ProcessNotification(XamarinMastering.Droid.GcmService service, NotificationManager notificationManager, Intent uiIntent, NotificationCompat.Builder builder, string title, string description, Bitmap largeIcon)
        {
            Notification notification = builder.SetContentIntent(PendingIntent.GetActivity(service, 0, uiIntent, 0))
                                        .SetSmallIcon(Resource.Drawable.icon)
                                        .SetLargeIcon(largeIcon)
                                        .SetTicker(title)
                                        .SetContentTitle(title)
                                        .SetContentText(description)
                                        .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification))
                                        .SetAutoCancel(true)
                                        .Build();

            notificationManager.Notify(1, notification);
        }
Ejemplo n.º 54
0
        void createNotification(string body, mPushNotify info)
        {
            var intent = new Intent(this, typeof(MainActivity));

            intent.PutExtra("type", info.Type); intent.PutExtra("why", info.Why); intent.PutExtra("objecter", info.Objecter); intent.PutExtra("message", info.Messgae);

            intent.AddFlags(ActivityFlags.ClearTop);
            var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);

            var defaultSoundUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification);

            #region Priority Numbers

            //
            // Summary:
            //     ///
            //     Lowest Android.App.Notification.Priority; these items might not be shown to the
            //     user except under special /// circumstances, such as detailed notification logs.
            //     ///
            //     ///
            // Min = -2,
            //
            // Summary:
            //     ///
            //     Lower Android.App.Notification.Priority, for items that are less important. The
            //     UI may choose to show these /// items smaller, or at a different position in
            //     the list, compared with your app's /// Android.App.Notification.PriorityDefault
            //     items. ///
            //     ///
            //Low = -1,
            //
            // Summary:
            //     ///
            //     Default notification Android.App.Notification.Priority. If your application does
            //     not prioritize its own /// notifications, use this value for all notifications.
            //     ///
            //     ///
            //Default = 0,
            //
            // Summary:
            //     ///
            //     Higher Android.App.Notification.Priority, for more important notifications or
            //     alerts. The UI may choose to /// show these items larger, or at a different position
            //     in notification lists, compared with /// your app's Android.App.Notification.PriorityDefault
            //     items. ///
            //     ///
            // High = 1,
            //
            // Summary:
            //     ///
            //     Highest Android.App.Notification.Priority, for your application's most important
            //     items that require the /// user's prompt attention or input. ///
            //     ///
            //Max = 2
            #endregion
            var notificationBuilder = new NotificationCompat.Builder(this);

            if (!String.IsNullOrEmpty(info.ImgUrl))
            {
                var imageBitmap = GetImageBitmapFromUrl(info.ImgUrl);



                notificationBuilder = new NotificationCompat.Builder(this)
                                      .SetPriority(1)
                                      .SetSmallIcon(Resource.Drawable.ic_logo)
                                      .SetContentTitle(info.Title)
                                      .SetContentText(body)
                                      .SetAutoCancel(true)
                                      .SetStyle(new NotificationCompat.BigPictureStyle().BigPicture(imageBitmap).SetBigContentTitle(body))
                                      .SetSound(defaultSoundUri)
                                      .SetContentIntent(pendingIntent);
            }
            else
            {
                notificationBuilder = new NotificationCompat.Builder(this)
                                      .SetPriority(1)
                                      .SetSmallIcon(Resource.Drawable.ic_logo)
                                      .SetContentTitle("Grid Central")
                                      .SetContentText(body)
                                      .SetAutoCancel(true)
                                      .SetStyle(new NotificationCompat.BigTextStyle().BigText(body))
                                      .SetSound(defaultSoundUri)
                                      .SetVibrate(new long[] { 1000, 1000 })
                                      .SetContentIntent(pendingIntent);
            }



            //var notify = new NotificationCompat.BigTextStyle(notificationBuilder).BigText(body);



            var notificationManger = NotificationManager.FromContext(this);
            notificationManger.Notify(0, notificationBuilder.Build());
        }
Ejemplo n.º 55
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Window.RequestFeature(WindowFeatures.NoTitle);
            SetContentView(Resource.Layout.PageMainStart);

            InitFields();

            if (LoginActivity.StaticLocationClass.Name != null)
            {
                int i;
                mStorages.Count();
                mCurrentLocation.Text = LoginActivity.StaticLocationClass.Name;
                for (i = 0; mStorages.Count() > i; i++)
                {
                    int mCounter = 0;
                    if (mStorages[i].Id == LoginActivity.StaticLocationClass.Id)
                    {
                        for (int j = 0; mInventories.Count > j; j++)
                        {
                            if (mInventories[j].Id == mStorages[i].Id)
                            {
                                mCounter++;
                                mStockCounter.Text = mCounter.ToString();
                            }
                        }
                    }
                }
                mExpCounter.Text = "0";

                mRunOutCounter.Text = "0";
            }
            #region shortcut menu
            mRunOut.Click += (object sender, EventArgs args) =>
            {
                Intent nextActivity = new Intent(this, typeof(UseActivity));
                StartActivity(nextActivity);
            };
            mShopList.Click += (object sender, EventArgs args) =>
            {
                Intent nextActivity = new Intent(this, typeof(DrawerMenuActivity));
                StartActivity(nextActivity);
            };
            mAdd.Click += (object sender, EventArgs args) =>
            {
                Intent nextActivity = new Intent(this, typeof(ItemAddFormActivity));
                StartActivity(nextActivity);
            };
            mUse.Click += (object sender, EventArgs args) =>
            {
                Intent nextActivity = new Intent(this, typeof(UseActivity));
                StartActivity(nextActivity);
            };
            mStoragesMenu.Click += (object sender, EventArgs args) =>
            {
                Intent nextActivity = new Intent(this, typeof(StoragesActivity));
                StartActivity(nextActivity);
            };

            btnSend.Click += (s, e) =>
            {
                Bundle valuesSend = new Bundle();
                valuesSend.PutString("sendContent", "This is content awdawda");
                Intent newIntent = new Intent(this, typeof(UseActivity));
                newIntent.PutExtras(valuesSend);

                Android.Support.V4.App.TaskStackBuilder stackBuilder = Android.Support.V4.App.TaskStackBuilder.Create(this);
                stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(UseActivity)));
                stackBuilder.AddNextIntent(newIntent);
                PendingIntent resultPendingIntent  = stackBuilder.GetPendingIntent(0, (int)PendingIntentFlags.UpdateCurrent);
                NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                                                     .SetAutoCancel(true)
                                                     .SetContentIntent(resultPendingIntent)
                                                     .SetContentTitle("You have new Notification")
                                                     .SetSmallIcon(Resource.Drawable.logoshopdiary)
                                                     .SetContentText("You have expired items");

                NotificationManager notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);
                notificationManager.Notify(ButtonClickNotification, builder.Build());
            };

            mBtnThreeStrips.Click += (object sender, EventArgs args) =>
            {
                Intent nextActivity = new Intent(this, typeof(DrawerMenuActivity));
                StartActivity(nextActivity);
            };
            #endregion
        }
        public static async Task CreateNotifications(LocationData location, List <WeatherAlert> alerts)
        {
            // Gets an instance of the NotificationManager service
            NotificationManagerCompat mNotifyMgr = NotificationManagerCompat.From(App.Context);

            InitChannel();

            // Create click intent
            // Start WeatherNow Activity with weather data
            Intent intent = new Intent(App.Context, typeof(MainActivity))
                            .SetAction(Widgets.WeatherWidgetService.ACTION_SHOWALERTS)
                            .PutExtra("data", location.ToJson())
                            .PutExtra(Widgets.WeatherWidgetService.ACTION_SHOWALERTS, true)
                            .SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask | ActivityFlags.ClearTask);
            PendingIntent clickPendingIntent = PendingIntent.GetActivity(App.Context, 0, intent, 0);

            // Build update
            foreach (WeatherAlert alert in alerts)
            {
                var alertVM = new WeatherAlertViewModel(alert);

                var iconBmp = ImageUtils.TintBitmap(
                    await BitmapFactory.DecodeResourceAsync(App.Context.Resources, GetDrawableFromAlertType(alertVM.AlertType)),
                    Color.Black);

                var title = String.Format("{0} - {1}", alertVM.Title, location.name);

                NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(App.Context, NOT_CHANNEL_ID)
                    .SetSmallIcon(Resource.Drawable.ic_error_white)
                    .SetLargeIcon(iconBmp)
                    .SetContentTitle(title)
                    .SetContentText(alertVM.ExpireDate)
                    .SetStyle(new NotificationCompat.BigTextStyle().BigText(alertVM.ExpireDate))
                    .SetContentIntent(clickPendingIntent)
                    .SetOnlyAlertOnce(true)
                    .SetAutoCancel(true)
                    .SetPriority(NotificationCompat.PriorityDefault) as NotificationCompat.Builder;

                if (Build.VERSION.SdkInt < BuildVersionCodes.N)
                {
                    // Tell service to remove stored notification
                    mBuilder.SetDeleteIntent(GetDeleteNotificationIntent((int)alertVM.AlertType));
                }

                if (Build.VERSION.SdkInt >= BuildVersionCodes.N ||
                    WeatherAlertNotificationService.GetNotificationsCount() >= MIN_GROUPCOUNT)
                {
                    mBuilder.SetGroup(TAG);
                }

                // Builds the notification and issues it.
                // Tag: location.query; id: weather alert type
                if (Build.VERSION.SdkInt < BuildVersionCodes.N)
                {
                    WeatherAlertNotificationService.AddNotication((int)alertVM.AlertType, title);
                }
                mNotifyMgr.Notify(location.query, (int)alertVM.AlertType, mBuilder.Build());
            }

            bool buildSummary = false;

            if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
            {
                try
                {
                    NotificationManager mNotifyMgrV23 = (NotificationManager)App.Context.GetSystemService(App.NotificationService);
                    var statNotifs = mNotifyMgrV23.GetActiveNotifications();

                    if (statNotifs?.Length > 0)
                    {
                        buildSummary = statNotifs.Count(not => location.query.Equals(not.Tag)) >= MIN_GROUPCOUNT;
                    }
                }
                catch (Exception ex)
                {
                    Logger.WriteLine(LoggerLevel.Debug, ex, "SimpleWeather: {0}: error accessing notifications", LOG_TAG);
                }
            }
            else
            {
                buildSummary = WeatherAlertNotificationService.GetNotificationsCount() >= MIN_GROUPCOUNT;
            }

            if (buildSummary)
            {
                // Notification inboxStyle for grouped notifications
                var inboxStyle = new NotificationCompat.InboxStyle();

                if (Build.VERSION.SdkInt < BuildVersionCodes.N)
                {
                    // Add active notification titles to summary notification
                    foreach (var notif in WeatherAlertNotificationService.GetNotifications())
                    {
                        mNotifyMgr.Cancel(location.query, notif.Key);
                        inboxStyle.AddLine(notif.Value);
                    }

                    inboxStyle.SetBigContentTitle(App.Context.GetString(Resource.String.title_fragment_alerts));
                    inboxStyle.SetSummaryText(location.name);
                }
                else
                {
                    inboxStyle.SetSummaryText(App.Context.GetString(Resource.String.title_fragment_alerts));
                }

                NotificationCompat.Builder mSummaryBuilder =
                    new NotificationCompat.Builder(App.Context, NOT_CHANNEL_ID)
                    .SetSmallIcon(Resource.Drawable.ic_error_white)
                    .SetContentTitle(App.Context.GetString(Resource.String.title_fragment_alerts))
                    .SetContentText(location.name)
                    .SetStyle(inboxStyle)
                    .SetGroup(TAG)
                    .SetGroupSummary(true)
                    .SetContentIntent(clickPendingIntent)
                    .SetOnlyAlertOnce(true)
                    .SetAutoCancel(true) as NotificationCompat.Builder;

                if (Build.VERSION.SdkInt < BuildVersionCodes.N)
                {
                    mSummaryBuilder.SetDeleteIntent(GetDeleteAllNotificationsIntent());
                }

                // Builds the summary notification and issues it.
                mNotifyMgr.Notify(location.query, SUMMARY_ID, mSummaryBuilder.Build());
            }
        }
Ejemplo n.º 57
0
        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);
        }
Ejemplo n.º 58
0
        private async void ShowNotification(Intent intent)
        {
            const string msgKey      = "msg";
            const string senderIdKey = "senderid";
            const string senderKey   = "sender";
            const string iconKey     = "icon";

            if (!intent.Extras.ContainsKey(msgKey) || !intent.Extras.ContainsKey(senderIdKey) ||
                !intent.Extras.ContainsKey(senderKey) || !intent.Extras.ContainsKey(iconKey))
            {
                return;
            }

            NotificationMessage notification = new NotificationMessage();

            notification.Title   = intent.Extras.GetString(senderKey);
            notification.Message = intent.Extras.GetString(msgKey);
            notification.IconUrl = intent.Extras.GetString(iconKey);
            notification.FromId  = int.Parse(intent.Extras.GetString(senderIdKey));

            Bitmap largeIconBitmap = await GetImageBitmapFromUrlAsync(EndPoints.BaseUrl + notification.IconUrl);

            var notificationManager = NotificationManagerCompat.From(this);

            Intent notificationIntent = null;

            int id = notification.FromId;

            //if user id came in then let's send them to that page.
            if (id <= 0)
            {
                id = Settings.GetNotificationId();
                notificationIntent = new Intent(this, typeof(WelcomeActivity));
            }
            else
            {
                notificationIntent = new Intent(this, typeof(ConversationActivity));
                notificationIntent.PutExtra(ConversationActivity.RecipientId, (long)id);
            }

            notificationIntent.AddFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask);
            var pendingIntent = PendingIntent.GetActivity(this, 0, notificationIntent, PendingIntentFlags.UpdateCurrent);

            var wearableExtender =
                new NotificationCompat.WearableExtender()
                .SetContentIcon(Resource.Drawable.ic_launcher);

            NotificationCompat.Action reply =
                new NotificationCompat.Action.Builder(Resource.Drawable.ic_stat_social_reply,
                                                      "Reply", pendingIntent)
                .Build();

            var builder = new NotificationCompat.Builder(this)
                          .SetContentIntent(pendingIntent)
                          .SetContentTitle(notification.Title)
                          .SetAutoCancel(true)
                          .SetSmallIcon(Resource.Drawable.ic_notification)
                          .SetLargeIcon(largeIconBitmap)
                          .SetContentText(notification.Message)
                          .AddAction(reply)
                          .Extend(wearableExtender);

            // Obtain a reference to the NotificationManager

            var notif = builder.Build();

            notif.Defaults = NotificationDefaults.All;             //add sound, vibration, led :)

            notificationManager.Notify(id, notif);
        }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: @Override public Boolean handleNotification(EngagementReachInteractiveContent content) throws RuntimeException
        public virtual bool?handleNotification(EngagementReachInteractiveContent content)
        {
            /* System notification case */
            if (content.SystemNotification)
            {
                /* Big picture handling */
                Bitmap bigPicture    = null;
                string bigPictureURL = content.NotificationBigPicture;
                if (bigPictureURL != null && Build.VERSION.SDK_INT >= 16)
                {
                    /* Schedule picture download if needed, or load picture if download completed. */
                    long?downloadId = content.DownloadId;
                    if (downloadId == null)
                    {
                        EngagementNotificationUtilsV11.downloadBigPicture(mContext, content);
                        return(null);
                    }
                    else
                    {
                        bigPicture = EngagementNotificationUtilsV11.getBigPicture(mContext, downloadId.Value);
                    }
                }

                /* Generate notification identifier */
                int notificationId = getNotificationId(content);

                /* Build notification using support lib to manage compatibility with old Android versions */
                NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);

                /* Icon for ticker and content icon */
                builder.SmallIcon = mNotificationIcon;

                /*
                 * Large icon, handled only since API Level 11 (needs down scaling if too large because it's
                 * cropped otherwise by the system).
                 */
                Bitmap notificationImage = content.NotificationImage;
                if (notificationImage != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                {
                    builder.LargeIcon = scaleBitmapForLargeIcon(mContext, notificationImage);
                }

                /* Texts */
                string notificationTitle   = content.NotificationTitle;
                string notificationMessage = content.NotificationMessage;
                string notificationBigText = content.NotificationBigText;
                builder.ContentTitle = notificationTitle;
                builder.ContentText  = notificationMessage;

                /*
                 * Replay: display original date and don't replay all the tickers (be as quiet as possible
                 * when replaying).
                 */
                long?notificationFirstDisplayedDate = content.NotificationFirstDisplayedDate;
                if (notificationFirstDisplayedDate != null)
                {
                    builder.When = notificationFirstDisplayedDate;
                }
                else
                {
                    builder.Ticker = notificationTitle;
                }

                /* Big picture */
                if (bigPicture != null)
                {
                    builder.Style = (new NotificationCompat.BigPictureStyle()).bigPicture(bigPicture).setBigContentTitle(notificationTitle).setSummaryText(notificationMessage);
                }

                /* Big text */
                else if (notificationBigText != null)
                {
                    builder.Style = (new NotificationCompat.BigTextStyle()).bigText(notificationBigText);
                }

                /* Vibration/sound if not a replay */
                if (notificationFirstDisplayedDate == null)
                {
                    int defaults = 0;
                    if (content.NotificationSound)
                    {
                        defaults |= Notification.DEFAULT_SOUND;
                    }
                    if (content.NotificationVibrate)
                    {
                        defaults |= Notification.DEFAULT_VIBRATE;
                    }
                    builder.Defaults = defaults;
                }

                /* Launch the receiver on action */
                Intent actionIntent = new Intent(INTENT_ACTION_ACTION_NOTIFICATION);
                EngagementReachAgent.setContentIdExtra(actionIntent, content);
                actionIntent.putExtra(INTENT_EXTRA_NOTIFICATION_ID, notificationId);
                Intent intent = content.Intent;
                if (intent != null)
                {
                    actionIntent.putExtra(INTENT_EXTRA_COMPONENT, intent.Component);
                }
                actionIntent.Package = mContext.PackageName;
                PendingIntent contentIntent = PendingIntent.getBroadcast(mContext, (int)content.LocalId, actionIntent, FLAG_CANCEL_CURRENT);
                builder.ContentIntent = contentIntent;

                /* Also launch receiver if the notification is exited (clear button) */
                Intent exitIntent = new Intent(INTENT_ACTION_EXIT_NOTIFICATION);
                exitIntent.putExtra(INTENT_EXTRA_NOTIFICATION_ID, notificationId);
                EngagementReachAgent.setContentIdExtra(exitIntent, content);
                exitIntent.Package = mContext.PackageName;
                PendingIntent deleteIntent = PendingIntent.getBroadcast(mContext, (int)content.LocalId, exitIntent, FLAG_CANCEL_CURRENT);
                builder.DeleteIntent = deleteIntent;

                /* Can be dismissed ? */
                Notification notification = builder.build();
                if (!content.NotificationCloseable)
                {
                    notification.flags |= Notification.FLAG_NO_CLEAR;
                }

                /* Allow overriding */
                if (onNotificationPrepared(notification, content))

                /*
                 * Submit notification, replacing the previous one if any (this should happen only if the
                 * application process is restarted).
                 */
                {
                    mNotificationManager.notify(notificationId, notification);
                }
            }

            /* Activity embedded notification case */
            else
            {
                /* Get activity */
                Activity activity = EngagementActivityManager.Instance.CurrentActivity.get();

                /* Cannot notify in app if no activity provided */
                if (activity == null)
                {
                    return(false);
                }

                /* Get notification area */
                string category             = content.Category;
                int    areaId               = getInAppAreaId(category).Value;
                View   notificationAreaView = activity.findViewById(areaId);

                /* No notification area, check if we can install overlay */
                if (notificationAreaView == null)
                {
                    /* Check overlay is not disabled in this activity */
                    Bundle activityConfig = EngagementUtils.getActivityMetaData(activity);
                    if (!activityConfig.getBoolean(METADATA_NOTIFICATION_OVERLAY, true))
                    {
                        return(false);
                    }

                    /* Inflate overlay layout and get reference to notification area */
                    View overlay = LayoutInflater.from(mContext).inflate(getOverlayLayoutId(category), null);
                    activity.addContentView(overlay, new LayoutParams(MATCH_PARENT, MATCH_PARENT));
                    notificationAreaView = activity.findViewById(areaId);
                }

                /* Otherwise check if there is an overlay containing the area to restore visibility */
                else
                {
                    View overlay = activity.findViewById(getOverlayViewId(category));
                    if (overlay != null)
                    {
                        overlay.Visibility = View.VISIBLE;
                    }
                }

                /* Make the notification area visible */
                notificationAreaView.Visibility = View.VISIBLE;

                /* Prepare area */
                prepareInAppArea(content, notificationAreaView);
            }

            /* Success */
            return(true);
        }
Ejemplo n.º 60
0
        private async Task Download(RssEnCaso download, bool isManual)
        {
            var    uri            = new Uri(download.AudioBoomUrl);
            string filename       = System.IO.Path.GetFileName(uri.LocalPath);
            int    notificationId = new Random().Next();


            ISharedPreferences prefs       = PreferenceManager.GetDefaultSharedPreferences(this);
            ISaveAndLoadFiles  saveAndLoad = new SaveAndLoadFiles_Android();
            Bitmap             bm          = null;

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

            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
            {
                NotificationChannel mChannel = new NotificationChannel(channel_id, channel_name, NotificationImportance.Default)
                {
                    Description = channel_description,
                    LightColor  = Color.Red
                };
                mChannel.EnableLights(true);
                mChannel.SetShowBadge(true);
                notificationManager.CreateNotificationChannel(mChannel);
            }

            NotificationCompat.Builder builder = new NotificationCompat.Builder(this.ApplicationContext, channel_id)
                                                 .SetAutoCancel(true)             // Dismiss from the notif. area when clicked
                                                 .SetContentTitle(download.Title) // Set its title
                                                 .SetSmallIcon(Resource.Mipmap.ic_launcher)
                                                 .SetProgress(100, 0, false)
                                                 .SetOnlyAlertOnce(true)
                                                 .SetContentText(this.ApplicationContext.GetString(Resource.String.download_service_downloading));

            if (bm != null)
            {
                builder.SetLargeIcon(bm);
            }

            if (isManual)
            {
                notificationManager.Notify(notificationId, builder.Build());
            }
            else
            {
                StartForeground(id, builder.Build());
            }

            int ant = 1;
            Progress <DownloadBytesProgress> progressReporter = new Progress <DownloadBytesProgress>();

            progressReporter.ProgressChanged += (s, args) =>
            {
                int perc = (int)(100 * args.PercentComplete);
                if (perc > ant)
                {
                    ant += 1;
                    builder.SetProgress(100, (int)(100 * args.PercentComplete), false);
                    if (isManual)
                    {
                        notificationManager.Notify(notificationId, builder.Build());
                    }
                    else
                    {
                        StartForeground(id, builder.Build());
                    }
                }
            };

            try
            {
                if (Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.M)
                {
                    Permission permissionCheck = this.ApplicationContext.CheckSelfPermission(Manifest.Permission.WriteExternalStorage);
                    if (permissionCheck != Permission.Granted)
                    {
                        throw new UnauthorizedAccessException();
                    }
                }
                Task <byte[]> downloadTask    = DownloadHelper.CreateDownloadTask(download.AudioBoomUrl, progressReporter);
                byte[]        bytesDownloaded = null;
                //try
                //{
                bytesDownloaded = await downloadTask;
                //}
                //catch (Exception ex1)
                //{
                //    if (ex1.Message.Contains("(404) Not Found"))
                //    {
                //        downloadTask = DownloadHelper.CreateDownloadTask(download.AudioBoomUrl, progressReporter);
                //        bytesDownloaded = await downloadTask;
                //    }
                //}

                ISaveAndLoadFiles saveFile = new SaveAndLoadFiles_Android();
                var path = saveFile.SaveByteAsync(filename, bytesDownloaded);

                MediaScannerConnection
                .ScanFile(this.ApplicationContext,
                          new string[] { path },
                          new string[] { "audio/*" }, null);

                var enCasoFile = LocalDatabase <EnCasoFile> .GetEnCasoFileDb().GetFirstUsingString("SavedFile", path);

                if (enCasoFile != null)
                {
                    LocalDatabase <EnCasoFile> .GetEnCasoFileDb().Delete(enCasoFile);
                }
                LocalDatabase <EnCasoFile> .GetEnCasoFileDb().Save(
                    new EnCasoFile()
                {
                    Title            = download.Title,
                    Description      = download.Description,
                    PubDate          = download.PubDate,
                    ImageUrl         = download.ImageUrl,
                    SavedFile        = path,
                    DownloadDateTime = DateTime.Now
                }
                    );

                Intent openIntent = new Intent(this.ApplicationContext, typeof(MainActivity));
                openIntent.PutExtra(General.ALARM_NOTIFICATION_EXTRA, (int)DownloadReturns.OpenFile);
                openIntent.PutExtra(General.ALARM_NOTIFICATION_FILE, path);
                openIntent.PutExtra(General.ALARM_NOTIFICATION_TITLE, download.Title);
                openIntent.PutExtra(General.ALARM_NOTIFICATION_IMAGE, download.ImageUrl);
                PendingIntent pIntent = PendingIntent.GetActivity(this.ApplicationContext, 0, openIntent, PendingIntentFlags.UpdateCurrent);

                builder
                .SetProgress(0, 0, false)
                .SetContentText(download.Description)
                .SetContentIntent(pIntent);

                notificationManager.Notify(notificationId, builder.Build());
            }
            catch (UnauthorizedAccessException)
            {
                builder
                .SetProgress(0, 0, false)
                .SetContentText(Resources.GetString(Resource.String.download_service_unauthorized_file_exception));
                notificationManager.Notify(notificationId, builder.Build());
            }
            catch (IOException)
            {
                builder
                .SetProgress(0, 0, false)
                .SetContentText(Resources.GetString(Resource.String.download_service_io_file_exception));
                notificationManager.Notify(notificationId, builder.Build());
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("full"))
                {
                    builder
                    .SetProgress(0, 0, false)
                    .SetContentText(Resources.GetString(Resource.String.download_service_disk_full));
                }
                else
                {
                    builder
                    .SetProgress(0, 0, false)
                    .SetContentText(Resources.GetString(Resource.String.download_service_lost_internet_connection));
                }
                if (isManual)
                {
                    notificationManager.Notify(notificationId, builder.Build());
                }
                else
                {
                    StartForeground(id, builder.Build());
                }
            }
        }