예제 #1
0
        public void Send(string title, string message)
        {
            //Get Activity
            MainActivity activity = Forms.Context as MainActivity;
            var          context  = activity.Window.Context;

            // Instantiate the builder and set notification elements:

            Android.App.Notification.Builder notificationBuilder = new Android.App.Notification.Builder(context)
                                                                   .SetSmallIcon(Resource.Drawable.icon)
                                                                   .SetContentTitle(title)
                                                                   .SetContentText(message)
                                                                   .SetDefaults(NotificationDefaults.Sound);

            // Build the notification:
            Android.App.Notification notification = notificationBuilder.Build();

            // Turn on vibrate:
            notification.Defaults |= NotificationDefaults.Vibrate;

            //Auto cancel will remove the notification once the user touches it
            notification.Flags = NotificationFlags.AutoCancel;

            // Get the notification manager:
            NotificationManager notificationManager =
                context.GetSystemService(Context.NotificationService) as NotificationManager;

            // Publish the notification:
            notificationManager.Notify(NOTIFICATION_ID, notification);
        }
예제 #2
0
        public override void OnReceive(Context context, Intent intent)
        {
            PowerManager pm = (PowerManager)context.GetSystemService(Context.PowerService);
            PowerManager.WakeLock w1 = pm.NewWakeLock (WakeLockFlags.Full | WakeLockFlags.AcquireCausesWakeup | WakeLockFlags.OnAfterRelease, "NotificationReceiver");
            w1.Acquire ();

            //Toast.MakeText (context, "Received intent!", ToastLength.Short).Show ();
            var nMgr = (NotificationManager)context.GetSystemService (Context.NotificationService);
            var notification = new Notification (Resource.Drawable.Icon, context.Resources.GetString(Resource.String.ReminderTitle));
            //Clicking the pending intent does not go to the Home Activity Screen, but to the last activity that was active before leaving the app
            var pendingIntent = PendingIntent.GetActivity (context, 0, new Intent (context, typeof(Home)), PendingIntentFlags.UpdateCurrent);
            //Notification should be language specific
            notification.SetLatestEventInfo (context, context.Resources.GetString(Resource.String.ReminderTitle), context.Resources.GetString(Resource.String.ReminderText), pendingIntent);
            notification.Flags |= NotificationFlags.AutoCancel;
            nMgr.Notify (0, notification);

            Vibrator vibrator = (Vibrator) context.GetSystemService(Context.VibratorService);
            if (vibrator != null)
                vibrator.Vibrate(400);

            w1.Release ();

            //check these pages for really waking up the device
            // http://stackoverflow.com/questions/6864712/android-alarmmanager-not-waking-phone-up
            // https://forums.xamarin.com/discussion/7490/alarm-manager

            //it's good to use the alarm manager for tasks that should last even days:
            // http://stackoverflow.com/questions/14376470/scheduling-recurring-task-in-android/
        }
        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            _recordAudioActivity = new RecordAudioActivity();

            //start recording some timed audio? 
            t = new System.Timers.Timer();
            t.Interval = 10000;
            t.Elapsed += new System.Timers.ElapsedEventHandler(TimerComplete);

            //start recording the audio
            StartRecording();
            //start the timer
            t.Start();
            //set app title
            App.SetTitle("Recording Audio");


            var nMgr = (NotificationManager)GetSystemService(NotificationService);
            var notification = new Notification(Resource.Drawable.icon, "Message from AutoResolve service - Recording Audio");
            var pendingIntent = PendingIntent.GetActivity(this, 0, new Intent(this, typeof(AudioBackgroundService)), 0);
            notification.SetLatestEventInfo(this, "AutoResolve Service Notification", "Message from demo service", pendingIntent);
            nMgr.Notify(0, notification);


            return StartCommandResult.NotSticky;
        }
        //public void TimerMethod()
        //{
        //    TimerExampleState s = new TimerExampleState();

        //    // Create the delegate that invokes methods for the timer.
        //    TimerCallback timerDelegate = new TimerCallback(LaunchNotification);

        //    // Create a timer that waits one second, then invokes every second.
        //    Timer timer = new Timer(timerDelegate, s, 1000, 1000);

        //    // Keep a handle to the timer, so it can be disposed.
        //    s.tmr = timer;

        //    // The main thread does nothing until the timer is disposed.
        //    while (s.tmr != null)
        //        Thread.Sleep(0);
        //    Console.WriteLine("Timer example done.");
        //}

        private void LaunchNotification(string title, string message)
        {
            // Get the notifications manager:
            NotificationManager notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;

            // Instantiate the notification builder:
            Android.App.Notification.Builder builder = new Android.App.Notification.Builder(this)
                                                       .SetContentTitle(title)
                                                       .SetContentText(message)
                                                       .SetSmallIcon(Resource.Drawable.ic_notification)
                                                       .SetAutoCancel(true);


            // Build the notification:
            Android.App.Notification notification = builder.Build();

            notification.Defaults |= NotificationDefaults.Sound;

            // Notification ID used for all notifications in this app.
            // Reusing the notification ID prevents the creation of
            // numerous different notifications as the user experiments
            // with different notification settings -- each launch reuses
            // and updates the same notification.
            const int notificationId = 1;

            // Launch notification:
            notificationManager.Notify(notificationId, notification);
        }
		protected async void HandleRegistration(Context context, Intent intent)
		{
			string registrationId = intent.GetStringExtra("registration_id");
			string error = intent.GetStringExtra("error");
			string unregistration = intent.GetStringExtra("unregistered");

			var nMgr = (NotificationManager)GetSystemService (NotificationService);

			if (!String.IsNullOrEmpty (registrationId)) {
				NativeRegistration = await Hub.RegisterNativeAsync (registrationId, new[] {"Native"});

				var notificationNativeRegistration = new Notification (Resource.Drawable.Icon, "Native Registered");
				var pendingIntentNativeRegistration = PendingIntent.GetActivity (this, 0, new Intent (this, typeof(MainActivity)), 0);
				notificationNativeRegistration.SetLatestEventInfo (this, "Native Reg.-ID", NativeRegistration.RegistrationId, pendingIntentNativeRegistration);
				nMgr.Notify (_messageId, notificationNativeRegistration);
				_messageId++;
			}
			else if (!String.IsNullOrEmpty (error)) {
				var notification = new Notification (Resource.Drawable.Icon, "Gcm Registration Failed.");
				var pendingIntent = PendingIntent.GetActivity (this, 0, new Intent (this, typeof(MainActivity)), 0);
				notification.SetLatestEventInfo (this, "Gcm Registration Failed", error, pendingIntent);
				nMgr.Notify (_messageId, notification);
				_messageId++;
			}
			else if (!String.IsNullOrEmpty (unregistration)) {
				if (NativeRegistration != null)
					await Hub.UnregisterAsync (NativeRegistration);

				var notification = new Notification (Resource.Drawable.Icon, "Unregistered successfully.");
				var pendingIntent = PendingIntent.GetActivity (this, 0, new Intent (this, typeof(MainActivity)), 0);
				notification.SetLatestEventInfo (this, "MyIntentService", "Unregistered successfully.", pendingIntent);
				nMgr.Notify (_messageId, notification);
				_messageId++;
			}
		}
예제 #6
0
        public override void OnReceive(Context context, Intent intent)
        {
            PowerManager pm = (PowerManager)context.GetSystemService(Context.PowerService);
            PowerManager.WakeLock w1 = pm.NewWakeLock (WakeLockFlags.Full | WakeLockFlags.AcquireCausesWakeup | WakeLockFlags.OnAfterRelease, "NotificationReceiver");
            w1.Acquire ();

            //Toast.MakeText (context, "Received intent!", ToastLength.Short).Show ();
            var nMgr = (NotificationManager)context.GetSystemService (Context.NotificationService);
            //var notification = new Notification (Resource.Drawable.Icon, context.Resources.GetString(Resource.String.ReminderTitle));
            var notification = new Notification (Resource.Drawable.Icon, context.Resources.GetString(Resource.String.ReminderTitle));
            //Clicking the pending intent does not go to the Home Activity Screen, but to the last activity that was active before leaving the app
            var pendingIntent = PendingIntent.GetActivity (context, 0, new Intent (context, typeof(Home)), PendingIntentFlags.UpdateCurrent);
            //Notification should be language specific
            notification.SetLatestEventInfo (context, context.Resources.GetString(Resource.String.ReminderTitle), context.Resources.GetString(Resource.String.InvalidationText), pendingIntent);
            notification.Flags |= NotificationFlags.AutoCancel;
            nMgr.Notify (0, notification);

            //			Vibrator vibrator = (Vibrator) context.GetSystemService(Context.VibratorService);
            //			if (vibrator != null)
            //				vibrator.Vibrate(400);

            //change shared preferences such that the questionnaire button can change its availability
            ISharedPreferences sharedPref = context.GetSharedPreferences("com.FSoft.are_u_ok.PREFERENCES",FileCreationMode.Private);
            ISharedPreferencesEditor editor = sharedPref.Edit();
            editor.PutBoolean("QuestionnaireActive", false );
            editor.Commit ();

            //insert a line of -1 into some DB values to indicate that the questions have not been answered at the scheduled time
            MoodDatabase dbMood = new MoodDatabase(context);
            ContentValues insertValues = new ContentValues();
            insertValues.Put("date", DateTime.Now.ToString("dd.MM.yy"));
            insertValues.Put("time", DateTime.Now.ToString("HH:mm"));
            insertValues.Put("mood", -1);
            insertValues.Put("people", -1);
            insertValues.Put("what", -1);
            insertValues.Put("location", -1);
            //use the old value of questionFlags
            Android.Database.ICursor cursor;
            cursor = dbMood.ReadableDatabase.RawQuery("SELECT date, QuestionFlags FROM MoodData WHERE date = '" + DateTime.Now.ToString("dd.MM.yy") + "'", null); // cursor query
            int alreadyAsked = 0; //default value: no questions have been asked yet
            if (cursor.Count > 0) { //data was already saved today and questions have been asked, so retrieve which ones have been asked
                cursor.MoveToLast (); //take the last entry of today
                alreadyAsked = cursor.GetInt(cursor.GetColumnIndex("QuestionFlags")); //retrieve value from last entry in db column QuestionFlags
            }
            insertValues.Put("QuestionFlags", alreadyAsked);
            dbMood.WritableDatabase.Insert ("MoodData", null, insertValues);

            //set the new alarm
            AlarmReceiverQuestionnaire temp = new AlarmReceiverQuestionnaire();
            temp.SetAlarm(context);

            w1.Release ();

            //check these pages for really waking up the device
            // http://stackoverflow.com/questions/6864712/android-alarmmanager-not-waking-phone-up
            // https://forums.xamarin.com/discussion/7490/alarm-manager

            //it's good to use the alarm manager for tasks that should last even days:
            // http://stackoverflow.com/questions/14376470/scheduling-recurring-task-in-android/
        }
예제 #7
0
		public override void OnReceive (Context context, Intent intent)
		{
			var nMgr = (NotificationManager)context.GetSystemService (Context.NotificationService);
			var notification = new Notification (Resource.Drawable.Icon, "New stock data is available");
			var pendingIntent = PendingIntent.GetActivity (context, 0, new Intent (context, typeof(StockActivity)), 0);
			notification.SetLatestEventInfo (context, "Stocks Updated", "New stock data is available", pendingIntent);
			nMgr.Notify (0, notification);
		}
		void StartServiceInForeground ()
		{
			var ongoing = new Notification (Resource.Drawable.icon, "DemoService in foreground");
			var pendingIntent = PendingIntent.GetActivity (this, 0, new Intent (this, typeof(DemoActivity)), 0);
			ongoing.SetLatestEventInfo (this, "DemoService", "DemoService is running in the foreground", pendingIntent);

			StartForeground ((int)NotificationFlags.ForegroundService, ongoing);
		}
		void SendNotification ()
		{
			var nMgr = (NotificationManager)GetSystemService (NotificationService);
			var notification = new Notification (Resource.Drawable.icon, "Message from demo service");
			var pendingIntent = PendingIntent.GetActivity (this, 0, new Intent (this, typeof(DemoActivity)), 0);
			notification.SetLatestEventInfo (this, "Demo Service Notification", "Message from demo service", pendingIntent);
			nMgr.Notify (0, notification);
		}
        /// <summary>
        /// Initializes a new instance of the <see cref="V3CustomNotification"/> class.
        /// </summary>
        public V3CustomNotification()
        {
            this.CurrentBytes = -1;
            this.TotalBytes = -1;
            this.notification = new Notification();
            this.expandedView = null;

            this.notification.Flags |= NotificationFlags.OngoingEvent;
        }
예제 #11
0
        void CreateNotification(string title, string desc)
        {
            var notificationManager = GetSystemService(NotificationService) as NotificationManager;

            var uiIntent = new Intent(this, typeof(PushActivity));

            var notification = new Notification(Android.Resource.Drawable.SymActionEmail, title) {Flags = NotificationFlags.AutoCancel};

            notification.SetLatestEventInfo(this, title, desc, PendingIntent.GetActivity(this, 0, uiIntent, 0));

            if (notificationManager != null) notificationManager.Notify(1, notification);
        }
예제 #12
0
 public override void OnReceive(Context c, Intent intent)
 {
     PowerManager pm = (PowerManager)c.GetSystemService(Context.PowerService);
     PowerManager.WakeLock wl = pm.NewWakeLock (WakeLockFlags.Partial, "Notificacion");
     wl.Acquire ();
     NotificationManager manager = (NotificationManager)c.GetSystemService (Context.NotificationService);
     Notification notification = new Notification (Resource.Drawable.icon, "Tareas pendientes");
     PendingIntent pendiente = PendingIntent.GetActivity (c, 0, new Intent (c, typeof(MainActivity)), 0);
     notification.SetLatestEventInfo (c, "Tareas pendientes", "Tienes tareas por hacer", pendiente);
     manager.Notify (0, notification);
     wl.Release ();
 }
예제 #13
0
        public override void OnReceive(Context context, Intent intent)
        {
            PowerManager powerManager = (PowerManager)context.GetSystemService(Context.PowerService);
            PowerManager.WakeLock wakeLock = powerManager.NewWakeLock(WakeLockFlags.Partial, "Notification Reciever");
            wakeLock.Acquire();

            var notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService);
            var notification = new Notification(Resource.Drawable.Icon, "New Meeting");
            var pendingIntent = PendingIntent.GetActivity(context, 0, new Intent(context, typeof(SplashScreenActivity)), 0);
            notification.SetLatestEventInfo(context, "New Meeting", "There is an ACM meeting today.", pendingIntent);
            notificationManager.Notify(0, notification);
            wakeLock.Release();
        }
예제 #14
0
        private void StartForeground()
        {
            var pendingIntent = PendingIntent.GetActivity (ApplicationContext, 0,
                new Intent (ApplicationContext, typeof(MainActivity)),
                PendingIntentFlags.UpdateCurrent);

            var notification = new Notification {
                TickerText = new Java.Lang.String ("PorAkÀ!"),
                Icon = Resource.Drawable.ic_action_icon
            };
            notification.Flags |= NotificationFlags.OngoingEvent;
            notification.SetLatestEventInfo (ApplicationContext,  "PorAkÀ.co","Es mas barato!", pendingIntent);
            StartForeground (101, notification);
        }
예제 #15
0
        public void Send(string title, string message, ActivityType activityType, int notificationID)
        {
            MainActivity activity = Forms.Context as MainActivity;
            var          context  = activity.Window.Context;

            // Setup an intent for SecondActivity:
            Intent secondIntent = new Intent(context, typeof(MainActivity));

            // Pass some information to SecondActivity:
            secondIntent.PutExtra("action", activityType.ToString());

            // Create a task stack builder to manage the back stack:
            TaskStackBuilder stackBuilder = TaskStackBuilder.Create(context);

            // Add all parents of SecondActivity to the stack:
            stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(MainActivity)));

            // Push the intent that starts SecondActivity onto the stack:
            stackBuilder.AddNextIntent(secondIntent);

            // Obtain the PendingIntent for launching the task constructed by stackbuilder. The
            // pending intent can be used only once (one shot):
            const int     pendingIntentId = 0;
            PendingIntent pendingIntent   =
                stackBuilder.GetPendingIntent(pendingIntentId, PendingIntentFlags.OneShot);

            // Instantiate the builder and set notification elements, including the pending intent:
            Android.App.Notification.Builder builder = new Android.App.Notification.Builder(context)
                                                       .SetContentIntent(pendingIntent)
                                                       .SetContentTitle(title)
                                                       .SetContentText(message)
                                                       .SetSmallIcon(Resource.Drawable.icon)
                                                       .SetDefaults(NotificationDefaults.Sound);

            // Build the notification:
            Android.App.Notification notification = builder.Build();

            // Turn on vibrate:
            notification.Defaults |= NotificationDefaults.Vibrate;

            // Get the notification manager:
            NotificationManager notificationManager =
                context.GetSystemService(Context.NotificationService) as NotificationManager;

            // Publish the notification:
            const int notificationId = 0;

            notificationManager.Notify(notificationId, notification);
        }
예제 #16
0
 private void PutNotificationOnBar()
 {
     var notification = new Notification(Resource.Drawable.Icon,
             "Buuubaaaaaxxx",
             System.Environment.TickCount);
     PendingIntent contentIntent = PendingIntent.GetActivity(this, 0,
             new Intent(this, typeof(StartAppActivity)),
             0);
     notification.SetLatestEventInfo(this,
             GetText(Resource.String.local_service_started),
             "Baaabaaaayyyy",
             contentIntent);
     var nm = (NotificationManager)GetSystemService(NotificationService);
     nm.Notify(Resource.String.local_service_started, notification);
 }
예제 #17
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 button1 = FindViewById<Button> (Resource.Id.button1);

			// Instantiate the builder and set notification elements:
			builder = new Notification.Builder (this)
				.SetContentTitle ("Test")
				.SetContentText ("This is test")
				.SetSmallIcon (Resource.Drawable.Icon);

			// Build the notification:
			notification = builder.Build ();

			// Get the notification manager:
			notificationManger = GetSystemService (Context.NotificationService) as NotificationManager;

			const int notificationId = 0;

			button.Click += delegate {
				// Publish the notification:
				notificationManger.Notify (notificationId,notification);
				button.Text = string.Format ("{0} clicks!", count++);
			};

			button1.Click += delegate {
				builder = new Notification.Builder (this)
					.SetContentTitle ("Updated Test")
					.SetContentText ("This is updated test")
					.SetDefaults(NotificationDefaults.Sound | NotificationDefaults.Vibrate)
					.SetSmallIcon (Resource.Drawable.Icon);

				// Build the notification:
				notification = builder.Build ();

				// Publish the notification:
				notificationManger.Notify (notificationId,notification);

				button.Text = string.Format ("{0} clicks!", count++);
			};
		}
예제 #18
0
        private static void scheduleNotification(int notificationId, Notification notification, DateTimeOffset scheduleAt)
        {
            var alarmManager = (AlarmManager)Application.Context.GetSystemService(Context.AlarmService);
            var scheduledNotificationIntent = new Intent(Application.Context, typeof(SmartAlertCalendarEventBroadcastReceiver));

            scheduledNotificationIntent.SetData(getSmartAlertIdentifierUri(notificationId));
            scheduledNotificationIntent.PutExtra(SmartAlertCalendarEventBroadcastReceiver.NotificationId, notificationId);
            scheduledNotificationIntent.PutExtra(SmartAlertCalendarEventBroadcastReceiver.Notification, notification);

            cancelExistingPendingIntentIfNecessary(notificationId, scheduledNotificationIntent, alarmManager);

            var pendingIntent  = PendingIntent.GetBroadcast(Application.Context, notificationId, scheduledNotificationIntent, PendingIntentFlags.CancelCurrent);
            var futureInMillis = (long)(scheduleAt - DateTimeOffset.Now).TotalMilliseconds;

            alarmManager.SetExact(AlarmType.ElapsedRealtimeWakeup, SystemClock.ElapsedRealtime() + futureInMillis, pendingIntent);
        }
        /// <summary>
        /// This will be called once for every intent.
        /// </summary>
        /// <param name="intent">Intent.</param>
        /// <param name="flags">Flags.</param>
        /// <param name="startId">Start identifier.</param>
        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            // Can use intent to pass data to the service.
            var val = intent.GetStringExtra(IntentValueKey);

            Toast.MakeText(this, $"OnStartCommand({val})", ToastLength.Long).Show();

            var notification = new Notification(Resource.Drawable.Icon, "Service running in the foreground!");
            var notificationIntent = new Intent(this, typeof(MainActivity));
            var pendingIntent = PendingIntent.GetActivity(this, 0, notificationIntent, 0);
            notification.SetLatestEventInfo(this, "Foreground Service", "Tap to to to App", pendingIntent);
            StartForeground((int)NotificationFlags.ForegroundService, notification);

            // Regular Service (unlike IntentService) runs on the main thread so we must take care of threading here.
            Task.Run(() => {
                for(int i = 1; i < 999 && !this.cts.IsCancellationRequested; i++)
                {
                    MainActivity.L($"Processing foreground service...{i}");
                    Thread.Sleep(1000);
                }

                // Stop when done. There is an override that takes an integer parameter. That's the start ID. The service will then only stop
                // if the current start ID matches the one passed to StopSelf(). This prevents stopping the service internally if there are still Intents pending with
                // a higher start ID. (Again: stopping stops the ENTIRE service, not just this current workload!)
                if(!this.cts.IsCancellationRequested)
                {
                    this.StopSelf();
                }
            });

            // Sticky:
            // This mode makes sense for things that will be explicitly started and stopped to run for arbitrary periods of time, such as a service performing background music playback.
            // http://developer.android.com/reference/android/app/Service.html#START_STICKY

            // Redeliver Intent:
            // The service will not receive a onStartCommand(Intent, int, int) call with a null Intent because it will will only be re-started if it is not finished processing all Intents sent to it
            // (and any such pending events will be delivered at the point of restart).
            // http://developer.android.com/reference/android/app/Service.html#START_REDELIVER_INTENT

            // Not sticky:
            // This mode makes sense for things that want to do some work as a result of being started, but can be stopped when under memory pressure and will explicit start themselves again later to do more work.
            // An example of such a service would be one that polls for data from a server: it could schedule an alarm to poll every N minutes by having the alarm start its service.
            // When its onStartCommand(Intent, int, int) is called from the alarm, it schedules a new alarm for N minutes later, and spawns a thread to do its networking. If its process is killed while doing that check, the service will not be restarted until the alarm goes off.
            // http://developer.android.com/reference/android/app/Service.html#START_NOT_STICKY
            return StartCommandResult.Sticky;
        }
예제 #20
0
        public override void OnReceive(Context context, Intent intent)
        {
            var extra   = intent.GetStringExtra(NotificationKey);
            var id      = intent.GetStringExtra(NotificationBuilder.NotificationId);
            var options = DeserializeNotification(extra);

            if (!string.IsNullOrEmpty(options.AndroidOptions.HexColour) && options.AndroidOptions.HexColour.Substring(0, 1) != "#")
            {
                options.AndroidOptions.HexColour = "#" + options.AndroidOptions.HexColour;
            }

            // Show Notification
            Android.App.Notification.Builder builder = new Android.App.Notification.Builder(Application.Context)
                                                       .SetContentTitle(options.AndroidOptions.DebugShowIdInTitle ? "[" + id + "] " + options.Title : options.Title)
                                                       .SetContentText(options.Description)
                                                       .SetSmallIcon(options.AndroidOptions.SmallDrawableIcon.Value) // Must have small icon to display
                                                       .SetPriority((int)NotificationPriority.High)                  // Must be set to High to get Heads-up notification
                                                       .SetDefaults(NotificationDefaults.All)                        // Must also include vibrate to get Heads-up notification
                                                       .SetAutoCancel(true)
                                                       .SetColor(Color.ParseColor(options.AndroidOptions.HexColour));

            if (options.AndroidOptions.ForceOpenAppOnNotificationTap)
            {
                var clickIntent = new Intent(NotificationBuilder.OnClickIntent);
                clickIntent.PutExtra(NotificationBuilder.NotificationId, int.Parse(id));
                clickIntent.PutExtra(NotificationBuilder.NotificationForceOpenApp, options.AndroidOptions.ForceOpenAppOnNotificationTap);
                var pendingClickIntent = PendingIntent.GetBroadcast(Application.Context, (NotificationBuilder.StartId + int.Parse(id)), clickIntent, 0);
                builder.SetContentIntent(pendingClickIntent);
            }

            // Notification Channel
            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
            {
                var notificationChannelId = NotificationBuilder.GetOrCreateChannel(options.AndroidOptions.ChannelOptions);
                if (!string.IsNullOrEmpty(notificationChannelId))
                {
                    builder.SetChannelId(notificationChannelId);
                }
            }

            Android.App.Notification notification = builder.Build();

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

            notificationManager.Notify(Convert.ToInt32(id), notification);
        }
예제 #21
0
        public override void OnCreate()
        {
            base.OnCreate();

            _player = MediaPlayer.Create(this, Resource.Raw.M77_Bombay_Street_Up_In_The_Sky);
            _player.Looping = false;

            _notificationManager = (NotificationManager)GetSystemService(NotificationService);

            var notification = new Notification(Resource.Drawable.Icon, "Service started", DateTime.Now.Ticks);
            notification.Flags = NotificationFlags.NoClear;

            PendingIntent notificationIntent = PendingIntent.GetActivity(this, 0, new Intent(this, typeof(GiraffeActivity)), 0);
            notification.SetLatestEventInfo(this, "Music Service", "The music service has been started", notificationIntent);

            _notificationManager.Notify((int)Notifications.Started, notification);
        }
예제 #22
0
		protected override void OnMessage (Context context, Intent intent)
		{
			//Pull out the notification details
			string title = intent.Extras.GetString("title");
			string message = intent.Extras.GetString("message");

			//Create a new intent
			intent = new Intent(this, typeof(ConversationsActivity));

			//Create the notification
			var notification = new Notification(Android.Resource.Drawable.SymActionEmail, title);
			notification.Flags = NotificationFlags.AutoCancel;
			notification.SetLatestEventInfo(this, title, message, PendingIntent.GetActivity(this, 0, intent, 0));

			//Send the notification through the NotificationManager
			var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
			notificationManager.Notify(1, notification);
		}
예제 #23
0
        public CustomNavigationNotification(Context applicationContext)
        {
            notificationManager = (NotificationManager)applicationContext.GetSystemService(Context.NotificationService);

            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                NotificationChannel notificationChannel = new NotificationChannel(
                    CUSTOM_CHANNEL_ID, CUSTOM_CHANNEL_NAME, NotificationImportance.Low
                    );
                notificationManager.CreateNotificationChannel(notificationChannel);
            }

            customNotificationBuilder = new NotificationCompat.Builder(applicationContext, CUSTOM_CHANNEL_ID)
                                        .SetSmallIcon(Resource.Drawable.ic_navigation)
                                        .SetContentTitle("Custom Navigation Notification")
                                        .SetContentText("Display your own content here!")
                                        .SetContentIntent(CreatePendingStopIntent(applicationContext));

            customNotification = customNotificationBuilder.Build();
        }
예제 #24
0
        public void CreateNotification(int id, string titulo)
        {
            var buttonReceiver = new ButtonReceiver();

            Intent buttonIntent = new Intent(Android.App.Application.Context, typeof(ButtonReceiver));

            buttonIntent.PutExtra("notificationId", id);
            PendingIntent btPendingIntent = PendingIntent.GetBroadcast(Android.App.Application.Context, id, buttonIntent, PendingIntentFlags.OneShot);

            var builder = new NotificationCompat.Builder(Android.App.Application.Context, "location_notification")
                          .SetContentTitle(titulo)
                          .SetSmallIcon(Resource.Drawable.ic_today_white_24dp)
                          .SetAutoCancel(true)
                          .AddAction(new NotificationCompat.Action(Resource.Drawable.abc_btn_check_material, "DONETE :)", btPendingIntent));

            Android.App.Notification notification = builder.Build();
            notification.Flags |= NotificationFlags.NoClear;
            NotificationManager notificationManager = Android.App.Application.Context.GetSystemService(Android.Content.Context.NotificationService) as NotificationManager;

            notificationManager.Notify(id, notification);
        }
예제 #25
0
		/// <summary>
		/// By overriding this, we're specifying that the service is a _Started Service_, and therefore, we're
		/// supposed to manage it's lifecycle (shutting it down, for instance).
		/// </summary>
		public override StartCommandResult OnStartCommand (Android.Content.Intent intent, StartCommandFlags flags, int startId)
		{
			base.OnStartCommand (intent, flags, startId);

			Log.Debug (this.logTag, "Service1 Started");

			// let our users know that this service is running, because it'll be a foregrounded service
			// this isn't usually needed unless you're doing something like a music player app, because
			// services hardly every get recycle from memory pressure, especially sticky ones.
			var ongoingNotification = new Notification (Resource.Drawable.Icon, "Service1 Running Foreground");
			// the pending intent specifies the activity to launch when a user clicks on the notification
			// in this case, we want to take the user to the music player 
			var pendingIntent = PendingIntent.GetActivity (this, 0, new Intent (this, typeof(MainActivity)), 0);
			ongoingNotification.SetLatestEventInfo (this, logTag, "MainAppService is now runing in the foreground", pendingIntent);

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

			// tell the OS that if this service ever gets killed, to redilever the intent when it's started
			return StartCommandResult.RedeliverIntent;
		}
예제 #26
0
        public override void OnReceive(Context context, Intent intent)
        {
            PowerManager pm = (PowerManager)context.GetSystemService(Context.PowerService);
            PowerManager.WakeLock w1 = pm.NewWakeLock (WakeLockFlags.Full | WakeLockFlags.AcquireCausesWakeup | WakeLockFlags.OnAfterRelease, "NotificationReceiver");
            w1.Acquire ();

            //Toast.MakeText (context, "Received intent!", ToastLength.Short).Show ();
            var nMgr = (NotificationManager)context.GetSystemService (Context.NotificationService);
            var notification = new Notification (Resource.Drawable.Icon, context.Resources.GetString(Resource.String.ReminderTitle));
            //Clicking the pending intent does not go to the Home Activity Screen, but to the last activity that was active before leaving the app
            var pendingIntent = PendingIntent.GetActivity (context, 0, new Intent (context, typeof(Home)), PendingIntentFlags.UpdateCurrent);
            //Notification should be language specific
            notification.SetLatestEventInfo (context, context.Resources.GetString(Resource.String.ReminderTitle), context.Resources.GetString(Resource.String.ReminderText), pendingIntent);
            notification.Flags |= NotificationFlags.AutoCancel;
            nMgr.Notify (0, notification);

            Vibrator vibrator = (Vibrator) context.GetSystemService(Context.VibratorService);
            if (vibrator != null)
                vibrator.Vibrate(400);

            //change shared preferences such that the questionnaire button can change its availability
            ISharedPreferences sharedPref = context.GetSharedPreferences("com.FSoft.are_u_ok.PREFERENCES",FileCreationMode.Private);
            ISharedPreferencesEditor editor = sharedPref.Edit();
            editor.PutBoolean("QuestionnaireActive", true );
            editor.Commit ();

            //start an new alarm here for the invalidation period
            //Call setAlarm in the Receiver class
            AlarmReceiverInvalid temp = new AlarmReceiverInvalid();
            temp.SetAlarm (context); //call it with the context of the activity

            w1.Release ();

            //check these pages for really waking up the device
            // http://stackoverflow.com/questions/6864712/android-alarmmanager-not-waking-phone-up
            // https://forums.xamarin.com/discussion/7490/alarm-manager

            //it's good to use the alarm manager for tasks that should last even days:
            // http://stackoverflow.com/questions/14376470/scheduling-recurring-task-in-android/
        }
예제 #27
0
        public override void OnReceive(Context context, Intent intent)
        {
            var extra   = intent.GetStringExtra(NotificationKey);
            var id      = intent.GetStringExtra(NotificationBuilder.NotificationId);
            var options = DeserializeNotification(extra);

            // Show Notification
            Android.App.Notification.Builder builder = new Android.App.Notification.Builder(Application.Context)
                                                       .SetContentTitle(options.Title)
                                                       .SetContentText(options.Description)
                                                       .SetSmallIcon(options.AndroidOptions.SmallDrawableIcon.Value) // Must have small icon to display
                                                       .SetPriority((int)NotificationPriority.High)                  // Must be set to High to get Heads-up notification
                                                       .SetDefaults(NotificationDefaults.All)                        // Must also include vibrate to get Heads-up notification
                                                       .SetAutoCancel(true);

            Android.App.Notification notification = builder.Build();

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

            notificationManager.Notify(Convert.ToInt32(id), notification);
        }
        public override void OnCreate()
        {
            base.OnCreate();
            socket.On("notification", data =>
            {
                var e = JsonConvert.DeserializeObject <List <Device> >(data.ToString());
                Android.App.Notification.Builder builder = new Android.App.Notification.Builder(this)
                                                           .SetContentTitle("Turned On")
                                                           .SetContentText(e[0].name + " " + e[0].value + " W")
                                                           .SetDefaults(NotificationDefaults.Sound)
                                                           .SetSmallIcon(e[0].icon_id);

                // Build the notification:
                Android.App.Notification notification = builder.Build();

                // Get the notification manager:
                Android.App.NotificationManager notificationManager =
                    GetSystemService(Context.NotificationService) as NotificationManager;

                // Publish the notification:
                const int notificationId = 0;
                notificationManager.Notify(notificationId, notification);
            });
        }
예제 #29
0
        private void ShowNotification(Models.Notification _Notification)
        {
            Intent HClickIntent = new Intent(_context, (typeof(MainActivity)));

            HClickIntent.PutExtra("BY_EVENT", (_Notification.EVENT_IDENT != -1));
            if (_Notification.EVENT_IDENT != -1)
            {
                HClickIntent.PutExtra("EVENT_IDENT", _Notification.EVENT_IDENT);
            }
            else
            {
                if (_Notification.EVENT_DATE != "")
                {
                    HClickIntent.PutExtra("START_DATE", _Notification.EVENT_DATE);
                }
            }

            // Wir werden nicht mehr als 10000 notifications haben
            int           HPendingIntentIdPre = _Notification.IDENT + 10000;
            PendingIntent HPendingIntent      = PendingIntent.GetActivity(_context, HPendingIntentIdPre, HClickIntent, PendingIntentFlags.OneShot);


            Android.App.Notification.Builder HBuilder = new Android.App.Notification.Builder(_context)
                                                        .SetContentIntent(HPendingIntent)
                                                        .SetContentTitle(_Notification.CAPTION)
                                                        .SetContentText(_Notification.DESCRIPTION)
                                                        .SetDefaults(NotificationDefaults.Vibrate)
                                                        .SetAutoCancel(true)
                                                        .SetSmallIcon(Resource.Drawable.icon);

            Android.App.Notification HNotification = HBuilder.Build();

            NotificationManager HNotificationManager = _context.GetSystemService(MainActivity.NotificationService) as NotificationManager;

            HNotificationManager.Notify(_Notification.IDENT, HNotification);
        }
예제 #30
0
        public void ShowNotification(Int32 id, String title, String msg)
        {
            try {
                var activity = (Droid.MainActivity)Forms.Context;

                // Set up an intent so that tapping the notifications returns to this app:
                Intent intent = new Intent(activity, typeof(MainActivity));

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

                // Instantiate the builder and set notification elements, including pending intent:
                NotificationCompat.Builder builder = new NotificationCompat.Builder(activity, this.channel_id)
                                                     .SetContentIntent(pendingIntent)
                                                     .SetContentTitle(title)
                                                     .SetContentText(msg)
                                                     .SetSmallIcon(Resource.Drawable.ic_stat_info)
                                                     .SetLargeIcon(Android.Graphics.BitmapFactory.DecodeResource(Android.App.Application.Context.Resources, Resource.Drawable.ic_stat_info))
                                                     .SetSound(Android.Media.RingtoneManager.GetDefaultUri(Android.Media.RingtoneType.Notification))
                                                     .SetVibrate(new long[] { 1000, 1000 });

                // Build the notification:
                Android.App.Notification notification = builder.Build();

                // Get the notification manager:
                NotificationManager notificationManager =
                    activity.GetSystemService(Context.NotificationService) as NotificationManager;

                // Publish the notification:
                const int notificationId = 0;
                notificationManager.Notify(notificationId, notification);
            } catch (Exception ex) {
                Console.WriteLine("Notify: " + ex.Message.ToString());
            }
        }
예제 #31
0
        public INotificationResult Notify(Activity activity, INotificationOptions options)
        {
            var notificationId = _count;
            var id             = _count.ToString();

            _count++;

            Intent dismissIntent = new Intent(DismissedClickIntent);

            dismissIntent.PutExtra(NotificationId, notificationId);

            PendingIntent pendingDismissIntent = PendingIntent.GetBroadcast(activity.ApplicationContext, 123, dismissIntent, 0);

            Intent clickIntent = new Intent(OnClickIntent);

            clickIntent.PutExtra(NotificationId, notificationId);

            // Add custom args
            if (options.CustomArgs != null)
            {
                foreach (var arg in options.CustomArgs)
                {
                    clickIntent.PutExtra(arg.Key, arg.Value);
                }
            }

            PendingIntent pendingClickIntent = PendingIntent.GetBroadcast(activity.ApplicationContext, 123, clickIntent, 0);

            int smallIcon;

            if (options.AndroidOptions.SmallDrawableIcon.HasValue)
            {
                smallIcon = options.AndroidOptions.SmallDrawableIcon.Value;
            }
            else if (_androidOptions.SmallIconDrawable.HasValue)
            {
                smallIcon = _androidOptions.SmallIconDrawable.Value;
            }
            else
            {
                smallIcon = Android.Resource.Drawable.IcDialogInfo; // As last resort
            }
            Android.App.Notification.Builder builder = new Android.App.Notification.Builder(activity)
                                                       .SetContentTitle(options.Title)
                                                       .SetContentText(options.Description)
                                                       .SetSmallIcon(smallIcon)                     // Must have small icon to display
                                                       .SetPriority((int)NotificationPriority.High) // Must be set to High to get Heads-up notification
                                                       .SetDefaults(NotificationDefaults.All)       // Must also include vibrate to get Heads-up notification
                                                       .SetAutoCancel(true)                         // To allow click event to trigger delete Intent
                                                       .SetContentIntent(pendingClickIntent)        // Must have Intent to accept the click
                                                       .SetDeleteIntent(pendingDismissIntent);

            Android.App.Notification notification = builder.Build();

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

            notificationManager.Notify(notificationId, notification);

            var timer = new Timer(x => TimerFinished(id), null, TimeSpan.FromSeconds(7), TimeSpan.FromSeconds(100));

            var resetEvent = new ManualResetEvent(false);

            ResetEvent.Add(id, resetEvent);

            resetEvent.WaitOne(); // Wait for a result

            var notificationResult = EventResult[id];

            if (!options.IsClickable && notificationResult.Action == NotificationAction.Clicked)
            {
                notificationResult.Action = NotificationAction.Dismissed;
            }

            EventResult.Remove(id);
            ResetEvent.Remove(id);

            // Dispose of Intents and Timer
            pendingClickIntent.Cancel();
            pendingDismissIntent.Cancel();
            timer.Dispose();

            return(notificationResult);
        }
예제 #32
0
파일: Index.cs 프로젝트: eatage/AppTest
            public override View GetView(int position, View convertView, ViewGroup parent)
            {
                if (convertView != null)
                    return convertView;
                LayoutInflater mInflater = LayoutInflater.From(context);
                View view = null;
                view = mInflater.Inflate(Resource.Layout.Index_Item, null);
                ImageView image = view.FindViewById<ImageView>(Resource.Id.Index_ItemImage);
                TextView name = view.FindViewById<TextView>(Resource.Id.Index_ItemText);
                TextView no = view.FindViewById<TextView>(Resource.Id.Index_ItemText_no);
                switch (list[position])
                {
                    #region 录入补货
                    case "录入补货":
                        image.SetImageResource(Resource.Drawable.AccBook);
                        name.Text = list[position];
                        view.Click += delegate
                        {
                            //Intent intent = new Intent();
                            //intent.SetClass(context, typeof(Customer));
                            //context.StartActivity(intent);
                            context.StartActivity(typeof(Customer));
                        };
                        break;
                    #endregion
                    #region 购 物 车
                    case "购 物 车":
                        image.SetImageResource(Resource.Drawable.shoppingcart);
                        name.Text = list[position];
                        //if (Shopping.GetShoppingToStr() != "")
                        //    no.Visibility = ViewStates.Visible;
                        view.Click += delegate
                        {
                            context.StartActivity(typeof(OrderSave));
                        };
                        break;
                    #endregion
                    #region 本地订单
                    case "本地订单":
                        image.SetImageResource(Resource.Drawable.GetMain);
                        name.Text = list[position];
                        //int row = SqliteHelper.ExecuteNum("select count(*) from getmain where isupdate ='N'");
                        //if (row > 0)
                        //    no.Visibility = ViewStates.Visible;
                        view.Click += delegate
                        {
                            context.StartActivity(typeof(GetMian));
                        };
                        break;
                    #endregion
                    #region 订单查询
                    case "订单查询":
                        image.SetImageResource(Resource.Drawable.Replenishment);
                        name.Text = list[position];
                        view.Click += delegate
                        {
                            Intent intent = new Intent();
                            Bundle bu = new Bundle();
                            bu.PutString("name", "App/Dw_GetMain");
                            intent.PutExtras(bu);
                            intent.SetClass(context, typeof(Web));
                            context.StartActivity(intent);
                        };
                        break;
                    #endregion
                    #region 出货单查询
                    case "出货单查询":
                        image.SetImageResource(Resource.Drawable.OutOne);
                        name.Text = list[position];
                        view.Click += delegate
                        {
                            Intent intent = new Intent();
                            Bundle bu = new Bundle();
                            bu.PutString("name", "App/Dw_OutOne");
                            intent.PutExtras(bu);
                            intent.SetClass(context, typeof(Web));
                            context.StartActivity(intent);
                        };
                        break;
                    #endregion
                    #region 库存查询
                    case "库存查询":
                        image.SetImageResource(Resource.Drawable.btn_Stock);
                        name.Text = list[position];
                        view.Click += delegate
                        {
                            Intent intent = new Intent();
                            Bundle bu = new Bundle();
                            bu.PutString("name", "App/Dw_Stock");
                            intent.PutExtras(bu);
                            intent.SetClass(context, typeof(Web));
                            context.StartActivity(intent);
                        };
                        break;
                    #endregion
                    #region 刷新数据
                    case "刷新数据":
                        image.SetImageResource(Resource.Drawable.Refresh);
                        name.Text = list[position];
                        view.Click += delegate
                        {
                            AlertDialog.Builder builder = new AlertDialog.Builder(context);
                            builder.SetTitle("提示:");
                            builder.SetMessage("确认刷新所有数据吗?建议在WiFi环境下执行此操作");
                            builder.SetPositiveButton("确定", delegate
                            {
                                SysVisitor.CreateServerDB();
                                Intent intent = new Intent();
                                Bundle bu = new Bundle();
                                bu.PutString("name", "data");
                                bu.PutString("update", "update");
                                intent.PutExtras(bu);
                                intent.SetClass(context, typeof(Loading));
                                context.StartActivity(intent);
                            });
                            builder.SetNegativeButton("取消", delegate { });
                            builder.Show();
                        };
                        break;
                    #endregion
                    #region 注销登陆
                    case "注销登陆":
                        image.SetImageResource(Resource.Drawable.zhuxiao);
                        name.Text = list[position];
                        view.Click += delegate
                        {
                            _publicfuns.of_SetMySysSet("Login", "username", "");
                            _publicfuns.of_SetMySysSet("Login", "password", "");
                            _publicfuns.of_SetMySysSet("Login", "logindate", DateTime.Now.AddDays(-30).ToString());
                            Intent it = new Intent();
                            it.SetClass(context.ApplicationContext, typeof(MainActivity));
                            context.StartActivity(it);
                        };
                        break;
                    #endregion
                    #region 退出系统
                    case "退出系统":
                        image.SetImageResource(Resource.Drawable.btn_Exit);
                        name.Text = list[position];
                        view.Click += delegate
                        {
                            System.Threading.Thread.Sleep(500);
                            ContextWrapper cw = new ContextWrapper(context);
                            Intent exitIntent = new Intent(Intent.ActionMain);
                            exitIntent.AddCategory(Intent.CategoryHome);
                            exitIntent.SetFlags(ActivityFlags.NewTask);
                            cw.StartActivity(exitIntent);
                            Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
                        };
                        break;
                    #endregion
                    #region 检查更新
                    case "检查更新":
                        image.SetImageResource(Resource.Drawable.btn_update);
                        name.Text = list[position];
                        view.Click += delegate
                        {
                            view.Enabled = false;
                            string str = Core.Update.of_update(true);
                            view.Enabled = true;
                            if (str.Substring(0, 2) != "ER")
                            {
                                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                                builder.SetTitle("提示:");
                                builder.SetMessage("当前版本为" + _publicfuns.of_GetMySysSet("app", "vercode") + "服务器上最新版本为 " + str + " ,确定下载更新吗?");
                                builder.SetPositiveButton("确定", delegate
                                {
                                    Intent intent = new Intent();
                                    Bundle bu = new Bundle();
                                    bu.PutString("name", "download");
                                    intent.PutExtras(bu);
                                    intent.SetClass(context, typeof(Loading));
                                    context.StartActivity(intent);
                                });
                                builder.SetNegativeButton("取消", delegate { return; });
                                builder.Show();
                            }
                            else
                            {
                                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                                builder.SetTitle("提示:");
                                builder.SetMessage(str + " 当前版本为" + _publicfuns.of_GetMySysSet("app", "vercode"));
                                builder.SetPositiveButton("确定", delegate
                                {
                                    return;
                                });
                                builder.Show();
                            }

                        };
                        break;
                    #endregion
                    #region 录入回款
                    case "录入回款":
                        image.SetImageResource(Resource.Drawable.backmoneyrecord);
                        name.Text = list[position];
                        view.Click += delegate
                        {
                            //Intent intent = new Intent(Android.Provider.MediaStore.ActionImageCapture);
                            //string file = System.IO.Path.Combine(Android.OS.Environment.ExternalStorageDirectory.ToString(),
                            //    Android.OS.Environment.DirectoryDcim.ToString(), "test.jpg");
                            //outputFileUri = Android.Net.Uri.Parse(file);
                            //intent.PutExtra(Android.Provider.MediaStore.ExtraOutput, outputFileUri);
                            //activity.StartActivityForResult(intent, TAKE_PICTRUE);

                            Intent intent = new Intent();
                            Bundle bu = new Bundle();
                            bu.PutString("name", "backmoneyrecord");
                            bu.PutString("ischeck", "false");
                            intent.PutExtras(bu);
                            intent.SetClass(context, typeof(Customer));
                            context.StartActivity(intent);
                        };
                        break;
                    #endregion
                    #region 本地回款
                    case "本地回款":
                        image.SetImageResource(Resource.Drawable.GetBackmoney);
                        name.Text = list[position];
                        //int row = SqliteHelper.ExecuteNum("select count(*) from Backmoneyrecord  where isupdate ='N'");
                        //if (row > 0)
                        //    no.Visibility = ViewStates.Visible;
                        view.Click += delegate
                        {
                            context.StartActivity(typeof(GetBackmoney));
                        };
                        break;
                    #endregion
                    #region 消息通知
                    case "消息通知":
                        image.SetImageResource(Resource.Drawable.message);
                        int li_msg_count = 0;
                        try
                        {
                            //以后在后台刷新 防止网络不好时卡在启动页面
                            //li_msg_count = int.Parse(SysVisitor.Of_GetStr(SysVisitor.Get_ServerUrl()+ "/App/MsgList.aspx?select=num"));
                        }
                        catch { }
                        if (li_msg_count > 0)
                        {
                            no.Visibility = ViewStates.Visible;

                            Intent intent = new Intent();
                            Bundle bu = new Bundle();
                            bu.PutString("name", "App/GetAppMsg.ashx");
                            intent.PutExtras(bu);
                            intent.SetClass(context, typeof(Web));
                            nMgr = (NotificationManager)context.GetSystemService(Context.NotificationService);

                            Notification notify = new Notification(Resource.Drawable.Icon, "有新的通知消息");
                            //初始化点击通知后打开的活动
                            PendingIntent pintent = PendingIntent.GetActivity(context, 0, intent, PendingIntentFlags.UpdateCurrent);
                            //设置通知的主体
                            notify.SetLatestEventInfo(context, "有新的通知消息", "点击查看详细内容", pintent);
                            nMgr.Notify(0, notify);
                        }
                        name.Text = list[position];
                        view.Click += delegate
                        {
                            Intent intent = new Intent();
                            Bundle bu = new Bundle();
                            bu.PutString("name", "App/GetAppMsg.ashx");
                            intent.PutExtras(bu);
                            intent.SetClass(context, typeof(Web));
                            context.StartActivity(intent);
                        };
                        break;
                    #endregion
                    #region 即时通讯
                    case "即时通讯":
                        image.SetImageResource(Resource.Drawable.im3);
                        name.Text = list[position];
                        view.Click += delegate
                        {
                            context.StartActivity(typeof(Buddylist));
                        };
                        break;
                    #endregion
                    #region 系统设置
                    case "系统设置":
                        image.SetImageResource(Resource.Drawable.config);
                        name.Text = list[position];
                        view.Click += delegate
                        {
                            context.StartActivity(typeof(Config));
                        };
                        break;
                    #endregion
                    #region 拍照上传
                    case "拍照上传":
                        image.SetImageResource(Resource.Drawable.picture);
                        name.Text = list[position];
                        view.Click += delegate
                        {
                            context.StartActivity(typeof(PhotoBrowse));
                        };
                        break;
                    #endregion
                    #region 新品订货
                    case "新品订货":
                        image.SetImageResource(Resource.Drawable.AccBook_new);
                        name.Text = list[position];
                        view.Click += delegate
                        {
                            //Intent intent = new Intent(Android.Provider.MediaStore.ActionImageCapture);
                            //string file = System.IO.Path.Combine(Android.OS.Environment.ExternalStorageDirectory.ToString(),
                            //    Android.OS.Environment.DirectoryDcim.ToString(), "test.jpg");
                            //outputFileUri = Android.Net.Uri.Parse(file);
                            //intent.PutExtra(Android.Provider.MediaStore.ExtraOutput, outputFileUri);
                            //activity.StartActivityForResult(intent, TAKE_PICTRUE);

                            Intent intent = new Intent();
                            Bundle bu = new Bundle();
                            bu.PutString("name", "OrderCar");
                            bu.PutString("ischeck", "false");
                            intent.PutExtras(bu);
                            intent.SetClass(context, typeof(Customer));
                            context.StartActivity(intent);
                        };
                        break;
                    #endregion
                    #region 客户对账
                    case "客户对账":
                        image.SetImageResource(Resource.Drawable.BackMoney);
                        name.Text = list[position];
                        view.Click += delegate
                        {
                            Intent intent = new Intent();
                            Bundle bu = new Bundle();
                            bu.PutString("name", "WebDw_AccBook");
                            bu.PutString("ischeck", "false");
                            intent.PutExtras(bu);
                            intent.SetClass(context, typeof(Customer));
                            context.StartActivity(intent);
                        };
                        break;
                    #endregion
                    #region 回款查询
                    case "回款查询":
                        image.SetImageResource(Resource.Drawable.ShowBackMoneyreCord);
                        name.Text = list[position];
                        view.Click += delegate
                        {
                            Intent intent = new Intent();
                            Bundle bu = new Bundle();
                            bu.PutString("name", "App/Dw_BackMoneyreCord.aspx");
                            intent.PutExtras(bu);
                            intent.SetClass(context, typeof(Web));
                            context.StartActivity(intent);
                        };
                        break;
                    #endregion
                    #region 查看销价
                    case "查看销价":
                        image.SetImageResource(Resource.Drawable.SalePrice);
                        name.Text = list[position];
                        view.Click += delegate
                        {
                            context.StartActivity(typeof(SalePrice));
                        };
                        break;
                        #endregion
                }
                view.SetPadding(2, 4, 2, 8);
                return view;
            }
		void ShowDisconnected()
		{
			Intent startActivity = new Intent(this, typeof(TunnelService));
			startActivity.SetFlags(ActivityFlags.SingleTop);
			PendingIntent pendingIntent = PendingIntent.GetActivity(this, 0, startActivity, PendingIntentFlags.UpdateCurrent);
			
			
			var notification = new Notification(Resource.Drawable.addClient, "NXT Tunnel has stopped", DateTime.Now.Second);
			notification.SetLatestEventInfo(this, "NXT Tunnel", "Tunnel has stopped", pendingIntent);
			notificationManager.Notify( 0, notification);
		}
        public INotificationResult Notify(Activity activity, INotificationOptions options)
        {
            INotificationResult notificationResult = null;

            if (options != null)
            {
                var notificationId = 0;
                var id             = "";
                lock (_lock)
                {
                    notificationId = _count;
                    id             = _count.ToString();
                    _count++;
                }

                int smallIcon;

                if (options.AndroidOptions.SmallDrawableIcon.HasValue)
                {
                    smallIcon = options.AndroidOptions.SmallDrawableIcon.Value;
                }
                else if (_androidOptions.SmallIconDrawable.HasValue)
                {
                    smallIcon = _androidOptions.SmallIconDrawable.Value;
                }
                else
                {
                    smallIcon = Android.Resource.Drawable.IcDialogInfo; // As last resort
                }
                if (options.DelayUntil.HasValue)
                {
                    options.AndroidOptions.SmallDrawableIcon = smallIcon;
                    ScheduleNotification(id, options);
                    return(new NotificationResult()
                    {
                        Action = NotificationAction.NotApplicable, Id = notificationId
                    });
                }

                // Show Notification Right Now
                var dismissIntent = new Intent(DismissedClickIntent);
                dismissIntent.PutExtra(NotificationId, notificationId);

                var pendingDismissIntent = PendingIntent.GetBroadcast(Application.Context, (StartId + notificationId), dismissIntent, 0);

                var clickIntent = new Intent(OnClickIntent);
                clickIntent.PutExtra(NotificationId, notificationId);
                clickIntent.PutExtra(NotificationForceOpenApp, options.AndroidOptions.ForceOpenAppOnNotificationTap);

                // Add custom args
                if (options.CustomArgs != null)
                {
                    foreach (var arg in options.CustomArgs)
                    {
                        clickIntent.PutExtra(arg.Key, arg.Value);
                    }
                }

                var pendingClickIntent = PendingIntent.GetBroadcast(Application.Context, (StartId + notificationId), clickIntent, 0);

                if (!string.IsNullOrEmpty(options.AndroidOptions.HexColor) && options.AndroidOptions.HexColor.Substring(0, 1) != "#")
                {
                    options.AndroidOptions.HexColor = "#" + options.AndroidOptions.HexColor;
                }

                Android.App.Notification.Builder builder = new Android.App.Notification.Builder(Application.Context)
                                                           .SetContentTitle(options.Title)
                                                           .SetContentText(options.Description)
                                                           .SetSmallIcon(smallIcon)                     // Must have small icon to display
                                                           .SetPriority((int)NotificationPriority.High) // Must be set to High to get Heads-up notification
                                                           .SetDefaults(NotificationDefaults.All)       // Must also include vibrate to get Heads-up notification
                                                           .SetAutoCancel(true)                         // To allow click event to trigger delete Intent
                                                           .SetContentIntent(pendingClickIntent)        // Must have Intent to accept the click
                                                           .SetDeleteIntent(pendingDismissIntent)
                                                           .SetColor(Color.ParseColor(options.AndroidOptions.HexColor));

                try
                {
                    // Notification Channel
                    if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
                    {
                        var notificationChannelId = GetOrCreateChannel(options.AndroidOptions.ChannelOptions);
                        if (!string.IsNullOrEmpty(notificationChannelId))
                        {
                            builder.SetChannelId(notificationChannelId);
                        }
                    }
                }
                catch { }
                // System.MissingMethodException: Method 'Android.App.Notification/Builder.SetChannelId' not found.
                // I know this is bad, but I can't replicate it on any version, and many people are experiencing it.

                Android.App.Notification notification = builder.Build();

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

                notificationManager.Notify(notificationId, notification);

                if (options.DelayUntil.HasValue)
                {
                    return(new NotificationResult()
                    {
                        Action = NotificationAction.NotApplicable, Id = notificationId
                    });
                }

                var timer = new Timer(x => TimerFinished(id, options.ClearFromHistory, options.AllowTapInNotificationCenter), null, TimeSpan.FromSeconds(7), TimeSpan.FromMilliseconds(-1));

                var resetEvent = new ManualResetEvent(false);
                ResetEvent.Add(id, resetEvent);

                resetEvent.WaitOne(); // Wait for a result

                notificationResult = EventResult[id];

                if (!options.IsClickable && notificationResult.Action == NotificationAction.Clicked)
                {
                    notificationResult.Action = NotificationAction.Dismissed;
                    notificationResult.Id     = notificationId;
                }

                if (EventResult.ContainsKey(id))
                {
                    EventResult.Remove(id);
                }
                if (ResetEvent.ContainsKey(id))
                {
                    ResetEvent.Remove(id);
                }

                // Dispose of Intents and Timer
                pendingClickIntent.Cancel();
                pendingDismissIntent.Cancel();
                timer.Dispose();
            }
            return(notificationResult);
        }
예제 #35
0
 private static void CreateAlarmManager(Context ctx, Notification notification, DateTime date, NotificationOption not, int sessionId)
 {
     DateTime dtBasis = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
     AlarmManager alarmManager = (AlarmManager) ctx.GetSystemService(Context.AlarmService);
     alarmManager.Set(AlarmType.RtcWakeup, (long) date.ToUniversalTime().Subtract(dtBasis).TotalMilliseconds, GetPendingIntent(ctx, notification, not, sessionId));
 }
        private void TriggerStandardNotification(string text)
        {
            var sinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1);
            var now = (long) sinceEpoch.TotalMilliseconds;

            var notification = new Notification(Resource.Drawable.Icon, text, now);

            // This sets up an intent that will be attached to the notification, so when you click the
            // notification in the notification bar, it'll bring us back to 'LMSActivity' (our 'launcher')
            PendingIntent contentIntent = PendingIntent.GetActivity(this, 0, new Intent(this, typeof (LMSActivity)), 0);
            notification.SetLatestEventInfo(this,
                                            GetText(Resource.String.LocationMonitoringServiceLabel),
                                            text,
                                            contentIntent);

            // the 'R.S.LocationMonitoringServiceStarted' is an ID unique to this app's resources and is used as a key
            // to reference this notification message in future (like if we want to cancel it automatically).
            _notificationManager.Notify(Resource.String.LocationMonitoringServiceStarted, notification);
        }
		private void ShowNotification(string messageContent, string messageHeader, string conversationId, string senderId)
		{
			if (lastHeader == messageHeader)
			{
				return;
			}
			if (!ConversationActivity.ConversationActivityStateModel.IsInForeground || ConversationActivity.ConversationActivityStateModel.ConversationId != int.Parse(conversationId))
			{
				var nMgr = (NotificationManager)GetSystemService(NotificationService);
				var notification = new Notification(Resource.Drawable.Icon, messageContent);
				notification.Flags = NotificationFlags.AutoCancel;
				notification.Sound = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
				var intent = new Intent(this, typeof(ConversationActivity));
				intent.PutExtra(ExtrasKeys.CONVERSATION_ID, int.Parse(conversationId));
				intent.PutExtra(ExtrasKeys.ADDRESSEE_ID, senderId);
				var pendingIntent = PendingIntent.GetActivity(this, 0, intent, 0);
				notification.SetLatestEventInfo(this, "Nowa wiadomoϾ", messageContent, pendingIntent);
				nMgr.Notify(0, notification);
			}
			else
			{
				var message = new ConversationMessage();
				message.ConversationId = int.Parse(conversationId);
				message.MessageContent = messageContent;
				message.MessageHeader = messageHeader;
				ConversationActivity.ActivityInstance.AddMessage(message);
			}

			lastHeader = messageHeader;
		}
        /// <summary>
        /// The on download progress.
        /// </summary>
        /// <param name="progress">
        /// The progress.
        /// </param>
        public void OnDownloadProgress(DownloadProgressInfo progress)
        {
            this.progressInfo = progress;
            if (null != this.clientProxy)
            {
                this.clientProxy.OnDownloadProgress(progress);
            }

			if (progress.OverallTotal <= 0)
			{
				// we just show the text
				this.notification.TickerText = new String(this.currentTitle);
				this.notification.Icon = Android.Resource.Drawable.StatSysDownload;
				this.notification.SetLatestEventInfo(this.context, this.label, this.currentText, this.PendingIntent);
				this.currentNotification = this.notification;
			}
			else
			{
				this.customNotification.CurrentBytes = progress.OverallProgress;
				this.customNotification.TotalBytes = progress.OverallTotal;
				this.customNotification.Icon = Android.Resource.Drawable.StatSysDownload;
				this.customNotification.PendingIntent = this.PendingIntent;
				this.customNotification.Ticker = string.Format("{0}: {1}", this.label, this.currentText);
				this.customNotification.Title = this.label;
				this.customNotification.TimeRemaining = progress.TimeRemaining;
				this.currentNotification = this.customNotification.UpdateNotification(this.context);
			}

			this.notificationManager.Notify(NotificationId, this.currentNotification);
        }
예제 #39
0
        /// <summary>
        /// Обработчик события запуска службы
        /// </summary>
        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            // Защита
            if (isStarted)
            {
                return(StartCommandResult.NotSticky);
            }

            // Инициализация объектов настройки
            notManager = (NotificationManager)this.GetSystemService(Service.NotificationService);
            notBuilder = new NotificationCompat.Builder(this, ProgramDescription.AssemblyMainName.ToLower());

            // Создание канала (для Android O и выше)
            if (AndroidSupport.IsForegroundAvailable)
            {
                NotificationChannel channel = new NotificationChannel(ProgramDescription.AssemblyMainName.ToLower(),
                                                                      ProgramDescription.AssemblyMainName, NotificationImportance.High);

                // Настройка
                channel.Description          = ProgramDescription.AssemblyTitle;
                channel.LockscreenVisibility = NotificationVisibility.Public;

                // Запуск
                notManager.CreateNotificationChannel(channel);
                notBuilder.SetChannelId(ProgramDescription.AssemblyMainName.ToLower());
            }

            // Инициализация сообщений
            notBuilder.SetCategory("msg");                  // Категория "сообщение"
            notBuilder.SetColor(0x80FFC0);                  // Оттенок заголовков оповещений

            string launchMessage = "Нажмите, чтобы вернуться в основное приложение";

            notBuilder.SetContentText(launchMessage);
            notBuilder.SetContentTitle(ProgramDescription.AssemblyMainName);
            notBuilder.SetTicker(ProgramDescription.AssemblyMainName);

            // Настройка видимости для стартового сообщения
            notBuilder.SetDefaults(0);                      // Для служебного сообщения
            notBuilder.SetPriority(!AndroidSupport.IsForegroundAvailable ? (int)NotificationPriority.Default :
                                   (int)NotificationPriority.High);

            notBuilder.SetSmallIcon(Resource.Drawable.ic_not);
            if (AndroidSupport.IsLargeIconRequired)
            {
                notBuilder.SetLargeIcon(BitmapFactory.DecodeResource(this.Resources, Resource.Drawable.ic_not_large));
            }

            notBuilder.SetVisibility((int)NotificationVisibility.Public);

            notTextStyle = new NotificationCompat.BigTextStyle(notBuilder);
            notTextStyle.BigText(launchMessage);

            // Прикрепление ссылки для перехода в основное приложение
            masterIntent        = new Intent(this, typeof(NotificationLink));
            masterPendingIntent = PendingIntent.GetService(this, 0, masterIntent, PendingIntentFlags.Immutable);                // Android S+ req
            notBuilder.SetContentIntent(masterPendingIntent);

            // Стартовое сообщение
            Android.App.Notification notification = notBuilder.Build();
            StartForeground(notServiceID, notification);

            // Перенастройка для основного режима
            if (!AndroidSupport.IsForegroundAvailable)
            {
                notBuilder.SetDefaults(0);
                notBuilder.SetPriority((int)NotificationPriority.Max);
            }

            // Запуск петли
            this.RegisterReceiver(bcReceivers[0] = new BootReceiver(),
                                  new IntentFilter(Intent.ActionBootCompleted));
            this.RegisterReceiver(bcReceivers[1] = new BootReceiver(),
                                  new IntentFilter("android.intent.action.QUICKBOOT_POWERON"));

            handler.PostDelayed(runnable, frameLength);
            isStarted = true;

            return(StartCommandResult.NotSticky);
        }
예제 #40
0
 public virtual void SendNative(int id, Android.App.Notification notification)
 => this.NativeManager.Notify(id, notification);
예제 #41
0
        public static void Notification(String title, String ticker, String message, Intent intent, String key, String value)
        {
            ISharedPreferences pref = PreferenceManager.GetDefaultSharedPreferences(context);
            if(pref.GetBoolean("prefEnableNotifications", true))
            {
                int icon = Resource.Drawable.NotificationIcon;
                Notification notification = new Notification(icon, ticker);

                if(key != null && value != null)
                {
                    intent.PutExtra(key, value);
                }

                PendingIntent contentIntent = PendingIntent.GetActivity(context, 0, intent, 0);

                bool permNotification = pref.GetBoolean("prefEnablePermNotification", false);

                if (!permNotification)
                {
                    notification.Flags = NotificationFlags.AutoCancel;
                }

                notification.SetLatestEventInfo(context, "SteamDroid | " + title, message, contentIntent);

                notificationManager.Notify(1, notification);
            }
        }
예제 #42
0
 private static PendingIntent GetPendingIntent(Context ctx, Notification notification, NotificationOption not, int sessionId)
 {
     // Creates an explicit intent for an Activity in your app
     Intent notificationIntent = new Intent(ctx, typeof(NotificationPublisher));
     int identifier = (not.isWorkshop) ? 1 : 0;
     int notificationId = Integer.ParseInt(identifier + sessionId.ToString() + not.mins);
     notificationIntent.PutExtra(NotificationPublisher.NOTIFICATION_ID, notificationId);
     notificationIntent.PutExtra(NotificationPublisher.NOTIFICATION, notification);
     return PendingIntent.GetBroadcast(ctx, notificationId, notificationIntent, PendingIntentFlags.UpdateCurrent);
 }
예제 #43
0
 private void SendNotification(string message)
 {
     var nMgr = (NotificationManager)this.GetSystemService(NotificationService);
     var notification = new Notification(Resource.Drawable.Icon, "Kotys Message");
     var intent = new Intent();
     intent.SetComponent(new ComponentName(this, "dart.androidapp.ContactsActivity"));
     var pendingIntent = PendingIntent.GetActivity(this, 0, intent, 0);
     notification.SetLatestEventInfo(this, message, message, pendingIntent);
     nMgr.Notify(0, notification);
 }
      public Builder(Context context) {
        Context = context;
        Notification = new Notification();

        Notification.When = Java.Lang.JavaSystem.CurrentTimeMillis();
        Notification.AudioStreamType = Stream.NotificationDefault;
        Priority = PriorityDefault;
      }
        /// <summary>
        /// Initializes a new instance of the <see cref="DownloadNotification"/> class.
        /// </summary>
        /// <param name="ctx">
        /// The ctx.
        /// </param>
        /// <param name="applicationLabel">
        /// The application label.
        /// </param>
        internal DownloadNotification(Context ctx, string applicationLabel)
        {
            this.clientState = DownloaderState.Unknown;
            this.context = ctx;
            this.label = applicationLabel;
            this.notificationManager =
                this.context.GetSystemService(Context.NotificationService).JavaCast<NotificationManager>();
            this.notification = new Notification();
			this.customNotification = CustomNotificationFactory.CreateCustomNotification();
            this.currentNotification = this.notification;
        }
예제 #46
0
 public void Notify(Android.App.Notification notification, ToastId toastId)
 => AndroidNotificationManager.NotificationManager.Notify(toastId.Tag, toastId.Id, notification);