Example #1
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);
		}
		public override void OnCreate ()
		{
			nm = (NotificationManager) GetSystemService (NotificationService);

			// Display a notification about us starting.  We put an icon in the status bar.
			ShowNotification ();
		}
Example #3
0
        public NotificationManager(AndroidContext context,
                                   IServiceProvider services,
                                   ISerializer serializer,
                                   IJobManager jobs,
                                   IRepository repository,
                                   ISettings settings)
        {
            this.context    = context;
            this.services   = services;
            this.serializer = serializer;
            this.jobs       = jobs;
            this.repository = repository;
            this.settings   = settings;

            // auto process intent?
            //this.context
            //    .WhenActivityStatusChanged()
            //    .Where(x => x.Status == ActivityState.Created)
            //    .Subscribe(x => TryProcessIntent(x.Activity.Intent));

            if (this.context.IsMinApiLevel(26))
            {
                this.newManager = Native.FromContext(context.AppContext);
            }
            else
            {
                this.compatManager = NotificationManagerCompat.From(context.AppContext);
            }
        }
        public Builder GetBuilder(Context context, ChannelId channelId)
        {
            Builder builder = new Builder(context);

            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                Channel channel = Channels[(int)channelId];

                if (channel.NotificationChannel == null)
                {
                    // Create a NotificationChannel
                    NotificationChannel notificationChannel = new NotificationChannel(channel.ChannelId, channel.ChannelName, channel.Importance);
                    notificationChannel.Description = " ";
                    notificationChannel.EnableLights(channel.Lights);
                    notificationChannel.EnableVibration(channel.Vibration);
                    notificationChannel.SetBypassDnd(channel.DoNotDisturb);
                    notificationChannel.LockscreenVisibility = channel.Visibility;

                    // Register the new NotificationChannel
                    NotificationManagerCompat notificationManager = GetManager(context);
                    notificationManager.CreateNotificationChannel(notificationChannel);

                    channel.NotificationChannel = notificationChannel;
                }

                builder.SetChannelId(channel.ChannelId);
            }
            return(builder);
        }
		public override void OnViewCreated (View view, Bundle savedInstanceState)
		{
			notificationManager = (NotificationManager)Activity.GetSystemService (Context.NotificationService);
			numberOfNotifications = view.FindViewById <TextView> (Resource.Id.number_of_notifications);
			var addNotification = view.FindViewById <Button> (Resource.Id.add_notification);

			addNotification.Click += (sender, e) => AddNotificationAndUpdateSummaries ();

			// Create a PendingIntent to be fired upon deletion of a Notification.
			var deleteIntent = new Intent (MainActivity.ACTION_NOTIFICATION_DELETE);
			deletePendingIntent = PendingIntent.GetBroadcast (Activity, REQUEST_CODE, deleteIntent, 0);
		}
        public override void OnCreate()
        {
            ApplicationMain.InitializeIfNeeded(this, this.Application);

            Log.Debug(Tag, "OnCreate");

            if (this._notificationManager == null)
            {
                this._notificationManager = (NotificationManager)this.GetSystemService(Context.NotificationService);
            }

            base.OnCreate();
        }
        public MediaNotificationManager(MusicService serv)
        {
            service = serv;
            UpdateSessionToken();

            notificationColor = ResourceHelper.GetThemeColor(service,
                Android.Resource.Attribute.ColorPrimary, Color.DarkGray);

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

            string pkg = service.PackageName;
            pauseIntent = PendingIntent.GetBroadcast(service, RequestCode,
                new Intent(ActionPause).SetPackage(pkg), PendingIntentFlags.CancelCurrent);
            playIntent = PendingIntent.GetBroadcast(service, RequestCode,
                new Intent(ActionPlay).SetPackage(pkg), PendingIntentFlags.CancelCurrent);
            previousIntent = PendingIntent.GetBroadcast(service, RequestCode,
                new Intent(ActionPrev).SetPackage(pkg), PendingIntentFlags.CancelCurrent);
            nextIntent = PendingIntent.GetBroadcast(service, RequestCode,
                new Intent(ActionNext).SetPackage(pkg), PendingIntentFlags.CancelCurrent);

            notificationManager.CancelAll ();

            mCb.OnPlaybackStateChangedImpl = (state) => {
                playbackState = state;
                LogHelper.Debug (Tag, "Received new playback state", state);
                if (state != null && (state.State == PlaybackStateCode.Stopped ||
                    state.State == PlaybackStateCode.None)) {
                    StopNotification ();
                } else {
                    Notification notification = CreateNotification ();
                    if (notification != null) {
                        notificationManager.Notify (NotificationId, notification);
                    }
                }
            };

            mCb.OnMetadataChangedImpl = (meta) => {
                metadata = meta;
                LogHelper.Debug (Tag, "Received new metadata ", metadata);
                Notification notification = CreateNotification ();
                if (notification != null) {
                    notificationManager.Notify (NotificationId, notification);
                }
            };

            mCb.OnSessionDestroyedImpl = () => {
                LogHelper.Debug (Tag, "Session was destroyed, resetting to the new session token");
                UpdateSessionToken ();
            };
        }
        public AndroidNotificationManager ()
        {
            ctx = ServiceContainer.Resolve<Context> ();
            notificationManager = (NotificationManager)ctx.GetSystemService (Context.NotificationService);
            runningBuilder = CreateRunningNotificationBuilder (ctx);
            idleBuilder = CreateIdleNotificationBuilder (ctx);
            propertyTracker = new PropertyChangeTracker ();

            TimeEntryManager = ServiceContainer.Resolve<ActiveTimeEntryManager> ();
            binding = this.SetBinding (() => TimeEntryManager.ActiveTimeEntry).WhenSourceChanges (OnActiveTimeEntryChanged);

            var bus = ServiceContainer.Resolve<MessageBus> ();
            subscriptionSettingChanged = bus.Subscribe<SettingChangedMessage> (OnSettingChanged);
        }
        public ANotificationChannel Build()
        {
            if (name == null)
            {
                throw new InvalidOperationException("name required");
            }
            if (id == null)
            {
                id = GenerateIdByName(name);
            }
            var nm = ANotificationManager.FromContext(Application.Context)
                     ?? throw new InvalidOperationException(ErrorStrings.KNotificationManagerError);
            var channel = nm.GetNotificationChannel(id);

            if (channel != null)
            {
                return(channel);
            }
            ANotificationImportance ni = this.notificationImportance != null
                ? (ANotificationImportance)(int)this.notificationImportance
                : ANotificationImportance.Default;
            var anc = new ANotificationChannel(id, name, ni);

            if (description != null)
            {
                anc.Description = description;
            }
            Apply(lights, anc.EnableLights);
            Apply(vibration, anc.EnableVibration);
#if __ANDROID_29__
            Apply(allowBubbles, anc.SetAllowBubbles);
#endif
            Apply(bypassDnd, anc.SetBypassDnd);
            if (group != null)
            {
                anc.Group = group;
            }
            Apply(showBadge, anc.SetShowBadge);
            if (vibrationPattern != null)
            {
                anc.SetVibrationPattern(vibrationPattern);
            }
            if (sound != null && audioAttributes != null)
            {
                anc.SetSound(sound, audioAttributes);
            }
            nm.CreateNotificationChannel(anc);
            return(anc);
        }
Example #10
0
        public static void Initialize(Activity activity)
        {
            audioManager = (AudioManager)activity.GetSystemService(Context.AudioService);

            mediaPlayer = MediaPlayer.Create(activity.ApplicationContext, Resource.Raw.Message);

            notificationManager = (NotificationManager)activity.GetSystemService(Context.NotificationService);
            vibrator = (Vibrator)activity.GetSystemService(Context.VibratorService);

            //context = activity.ApplicationContext;
            context = activity;

            isAlertsEnabled = true;
            isProgressEnabled = true;
        }
        public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId)
        {
            // Instantiate the builder and set notification elements:
            notificationBuilder = new Notification.Builder (this)
                .SetContentTitle ("Test Notification")
                .SetContentText ("This worked")
                .SetSmallIcon (Resource.Drawable.vbclogo);

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

            ParsePush.ParsePushNotificationReceived += ParsePush_ParsePushNotificationReceived;

                return StartCommandResult.Sticky;
        }
        public AndroidNotificationManager ()
        {
            ctx = ServiceContainer.Resolve<Context> ();
            notificationManager = (NotificationManager)ctx.GetSystemService (Context.NotificationService);
            runningBuilder = CreateRunningNotificationBuilder (ctx);
            idleBuilder = CreateIdleNotificationBuilder (ctx);

            currentTimeEntry = TimeEntryModel.FindRunning ();
            SyncNotification ();

            var bus = ServiceContainer.Resolve<MessageBus> ();
            subscriptionModelChanged = bus.Subscribe<ModelChangedMessage> (OnModelChanged);
            subscriptionSettingChanged = bus.Subscribe<SettingChangedMessage> (OnSettingChanged);
            subscriptionAuthChanged = bus.Subscribe<AuthChangedMessage> (OnAuthChanged);
        }
        public NotificationManagerCompat GetManager(Context context)
        {
            if (notificationManager == null)
            {
                lock (managerlock)
                {
                    if (notificationManager == null)
                    {
                        notificationManager = (NotificationManagerCompat)context.GetSystemService(Context.NotificationService);
                    }
                }
            }

            return(notificationManager);
        }
		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++);
			};
		}
Example #15
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            RequestWindowFeature(WindowFeatures.NoTitle);
            SetContentView(Resource.Layout.ChatMain);

            string name = Intent.GetStringExtra("name");
            //获取通知管理类
            nMgr = (NotificationManager)GetSystemService(NotificationService);
            ListView list = FindViewById<ListView>(Resource.Id.chatmain_list);
            Button btn = FindViewById<Button>(Resource.Id.chat_bottom_sendbutton);
            TextView Msg = FindViewById<TextView>(Resource.Id.chat_bottom_edittext);
            TextView txt_name = FindViewById<TextView>(Resource.Id.chat_contact_name);
            txt_name.Text = name;
            btn.Click += delegate
            {
                if (Msg.Text != "")
                {
                    OnBind(Msg.Text);
                    Msg.Text = "";
                    Msg.Selected = false;
                }
                else
                {
                    Msg.Focusable = false;
                }
            };
            OnBind("");
            list.ItemClick += new EventHandler<AdapterView.ItemClickEventArgs>(ListView_ItemClick);

            //测试Socket通信
            //string host = SysVisitor.DoGetHostAddresses("im1.36x.cn");
            //IPAddress ip = IPAddress.Parse(host);
            //Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //try
            //{
            //    clientSocket.Connect(new IPEndPoint(ip, 8885)); //配置服务器IP与端口
            //    Toast.MakeText(this, "连接服务器成功", ToastLength.Long).Show();
            //}
            //catch
            //{
            //    Toast.MakeText(this, "连接服务器失败", ToastLength.Long).Show();
            //    return;
            //}
            //int receiveLength = clientSocket.Receive(result);
            //Toast.MakeText(this, "接收服务器消息:" + Encoding.ASCII.GetString(result, 0, receiveLength), ToastLength.Long).Show();
        }
Example #16
0
        private void CreateChannel()
        {
            manager = (Android.App.NotificationManager)Application.Context.GetSystemService(Context.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.EnableVibration(true);
                manager.CreateNotificationChannel(channel);
            }
        }
        public AndroidNotificationManager ()
        {
            ctx = ServiceContainer.Resolve<Context> ();
            notificationManager = (NotificationManager)ctx.GetSystemService (Context.NotificationService);
            runningBuilder = CreateRunningNotificationBuilder (ctx);
            idleBuilder = CreateIdleNotificationBuilder (ctx);
            propertyTracker = new PropertyChangeTracker ();

            timeEntryManager = ServiceContainer.Resolve<ActiveTimeEntryManager> ();
            timeEntryManager.PropertyChanged += OnActiveTimeEntryManagerPropertyChanged;

            var bus = ServiceContainer.Resolve<MessageBus> ();
            subscriptionSettingChanged = bus.Subscribe<SettingChangedMessage> (OnSettingChanged);

            SyncRunningModel ();
            SyncNotification ();
        }
Example #18
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);
        }
		public override void OnReceive (Context context, Intent intent)
		{
			
			
			if (notificationManager == null)
				notificationManager = (NotificationManager) context.GetSystemService (Context.NotificationService);
			Bundle bundle = intent.Extras;
			Log.Debug (TAG,"[CustomJPushReceiver] onReceive - "+intent.Action +",extrals:"+ printBundle(bundle));

			if (JPushInterface.ActionRegistrationId.Equals (intent.Action)) {
				//注册成功,获取广播中的registerid
				var regId = bundle.GetString(JPushInterface.ExtraRegistrationId);
				Log.Debug(TAG, "[CustomJPushReceiver] 接收Registration Id : " + regId);
			    
			}
			else if (JPushInterface.ActionMessageReceived.Equals (intent.Action)) {
				//接收自定义消息
				Log.Debug(TAG, "[CustomJPushReceiver] 接收到推送下来的自定义消息: " + bundle.GetString(JPushInterface.ExtraMessage));
				ProcessCustomMessage(context, bundle);
				
			} else if (JPushInterface.ActionNotificationReceived.Equals (intent.Action)) {
				//接收到用户通知
				int notifactionId = bundle.GetInt(JPushInterface.ExtraNotificationId);
				Log.Debug(TAG, "[CustomJPushReceiver] 接收到推送下来的通知的ID: " + notifactionId);

			} else if (JPushInterface.ActionNotificationOpened.Equals (intent.Action)) {

				Log.Debug(TAG, "[CustomJPushReceiver] 用户点击打开了通知");
				OpenNotification (context,bundle);

			} else if (JPushInterface.ActionRichpushCallback.Equals (intent.Action)) {
				Log.Debug(TAG, "[CustomJPushReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.GetString(JPushInterface.ExtraExtra));
				//在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码,比如打开新的Activity, 打开一个网页等..

			} else if (JPushInterface.ActionConnectionChange.Equals (intent.Action)) {
				//接收网络变化 连接/断开
				var connected = intent.GetBooleanExtra(JPushInterface.ExtraConnectionChange, false);
				Log.Warn(TAG, "[CustomJPushReceiver]" + intent.Action +" connected state change to "+connected);
			} else {
				//处理其它意图
				Log.Debug(TAG, "Unhandled intent - " + intent.Action);
			}
				

		}
        public void NotifyNewChapters(Context context, List <Chapter> chapters)
        {
            if (chapters.Count < 1)
            {
                return;
            }

            Builder builder = GetBuilder(context, ChannelId.NewChapter);

            builder.SetAutoCancel(true);
            builder.SetNumber(4);
            builder.SetOnlyAlertOnce(true);
            builder.SetContentTitle("1 New Chapter");
            builder.SetContentText(chapters[0].Title);

            Intent intent = new Intent(Intent.ActionView);

            intent.SetData(Uri.Parse(chapters[0].URL));
            intent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);
            PendingIntent pendingIntent = PendingIntent.GetActivity(context, (int)ChannelId.NewChapter, intent, PendingIntentFlags.OneShot);

            builder.SetContentIntent(pendingIntent);

            if (chapters.Count > 1)
            {
                builder.SetContentTitle($"{chapters.Count} New Chapters");
                builder.SetSubText($"and {chapters.Count - 1} more");

                var inboxStyle = new Notification.InboxStyle(GetBuilder(context, ChannelId.NewChapter));
                inboxStyle.SetBigContentTitle($"{chapters.Count} New Chapters");

                foreach (Chapter chapter in chapters)
                {
                    inboxStyle.AddLine(chapter.Title);
                }

                builder.SetStyle(inboxStyle);
            }
            //Bitmap icon = BitmapFactory.DecodeResource(context.Resources, Resource.Drawable.new_chapter_icon);
            builder.SetSmallIcon(Resource.Drawable.new_chapter_icon);

            NotificationManagerCompat notificationManager = GetManager(context);

            notificationManager.Notify((int)ChannelId.NewChapter, builder.Build());
        }
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            ActionBar.SetDisplayHomeAsUpEnabled(true);
            SetContentView(Resource.Layout.notify_demo);

            _region = this.GetBeaconAndRegion().Item2;

            _notificationManager = (NotificationManager)GetSystemService(NotificationService);
            _beaconManager = new BeaconManager(this);

            // Default values are 5s of scanning and 25s of waiting time to save CPU cycles.
            // In order for this demo to be more responsive and immediate we lower down those values.
            _beaconManager.SetBackgroundScanPeriod(TimeUnit.Seconds.ToMillis(1), 0);

            _beaconManager.EnteredRegion += (sender, e) => PostNotification("Entered region");
            _beaconManager.ExitedRegion += (sender, e) => PostNotification("Exited region");
        }
        public NotificationManager(AndroidContext context,
                                   IJobManager jobs,
                                   IRepository repository,
                                   ISettings settings)
        {
            this.context    = context;
            this.jobs       = jobs;
            this.repository = repository;
            this.settings   = settings;

            if ((int)Build.VERSION.SdkInt >= 26)
            {
                this.newManager = Native.FromContext(context.AppContext);
            }
            else
            {
                this.compatManager = NotificationManagerCompat.From(context.AppContext);
            }
        }
Example #23
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            RequestWindowFeature(WindowFeatures.NoTitle);
            SetContentView(Resource.Layout.ChatMain);

            //获取通知管理类
            nMgr = (NotificationManager)GetSystemService(NotificationService);
            ListView list = FindViewById<ListView>(Resource.Id.chatmain_list);
            Button btn = FindViewById<Button>(Resource.Id.chat_bottom_sendbutton);
            TextView Msg = FindViewById<TextView>(Resource.Id.chat_bottom_edittext);
            btn.Click += delegate
            {
                if (Msg.Text != "")
                {
                    OnBind(Msg.Text);
                    Msg.Text = "";
                    Msg.Selected = false;
                }
            };
            OnBind("");
        }
        async Task <NotificationResult> PrivateShowAsync(ToastId toastId, CancellationToken cancellationToken)
        {
            var tcs          = intentManager.RegisterToShowImmediatly(notificationBuilder, toastId);
            var notification = notificationBuilder.Build();
            var anm          = ANotificationManager.FromContext(Application.Context)
                               ?? throw new InvalidOperationException(ErrorStrings.KNotificationManagerError);

            using var timer = notificationBuilder.Timeout == Timeout.InfiniteTimeSpan ? null : new Timer(_ =>
            {
                if (notificationBuilder.CleanupOnTimeout)
                {
                    androidNotificationManager.Cancel(toastId);
                }
                tcs.TrySetResult(NotificationResult.TimedOut);
            }, null, notificationBuilder.Timeout, Timeout.InfiniteTimeSpan);
            androidNotificationManager.Notify(notification, toastId);
            if (cancellationToken.CanBeCanceled)
            {
                return(await tcs.WatchCancellationAsync(cancellationToken, () => androidNotificationManager.Cancel(toastId)));
            }
            return(await tcs.Task);
        }
Example #25
0
        private void SendNotification(PushNotification notificationDetails)
        {
            var notificationManager = NotificationManager.FromContext(this);

            var channelId = Covi.Configuration.Constants.PushNotificationsConstants.NotificationChannelName;

            var notificationId      = new Random().Next();
            var largeIcon           = BitmapFactory.DecodeResource(Resources, Resource.Mipmap.icon);
            var notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                .SetSmallIcon(Resource.Drawable.notification_icon)
                .SetLargeIcon(largeIcon)
                .SetPriority(NotificationCompat.PriorityHigh)
                .SetContentIntent(BuildIntentToShowMainActivity())
                .SetAutoCancel(true);

            if (!string.IsNullOrEmpty(notificationDetails.Title))
            {
                notificationBuilder.SetContentTitle(notificationDetails.Title);
            }

            if (!string.IsNullOrEmpty(notificationDetails.SubTitle))
            {
                notificationBuilder.SetSubText(notificationDetails.SubTitle);
            }

            if (!string.IsNullOrEmpty(notificationDetails.Description))
            {
                notificationBuilder.SetContentText(notificationDetails.Description);
                notificationBuilder.SetStyle(new NotificationCompat.BigTextStyle().BigText(notificationDetails.Description));
            }

            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                notificationBuilder.SetChannelId(Covi.Configuration.Constants.PushNotificationsConstants.NotificationChannelName);
            }

            notificationManager.Notify(notificationId, notificationBuilder.Build());
        }
        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);
            });
        }
        /// <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;
        }
Example #28
0
        public override void OnCreate()
        {
            base.OnCreate();
              mediaPlayer = new MediaPlayer();
              mediaPlayer.SetAudioStreamType(Stream.Music);
              mediaPlayer.SetDataSource(StreamAddress);

              mediaPlayer.Prepared += MediaPlayerPrepared;

              mediaSession = new MediaSession(this, PackageName);

              notificationManager = (NotificationManager)GetSystemService(NotificationService);
        }
		public override void OnCreate (Bundle savedInstanceState)
		{
			base.OnCreate (savedInstanceState);
			notificationManager = (NotificationManager)Activity.GetSystemService (Context.NotificationService);
		}
        public void SetService(AndroidSensusService service)
        {
            _service = service;

            if (_service == null)
            {
                if (_connectivityManager != null)
                    _connectivityManager.Dispose();

                if (_notificationManager != null)
                    _notificationManager.Dispose();

                if (_textToSpeech != null)
                    _textToSpeech.Dispose();

                if (_wakeLock != null)
                    _wakeLock.Dispose();
            }
            else
            {
                _connectivityManager = _service.GetSystemService(Context.ConnectivityService) as ConnectivityManager;
                _notificationManager = _service.GetSystemService(Context.NotificationService) as NotificationManager;
                _textToSpeech = new AndroidTextToSpeech(_service);
                _wakeLock = (_service.GetSystemService(Context.PowerService) as PowerManager).NewWakeLock(WakeLockFlags.Partial, "SENSUS");
                _wakeLockAcquisitionCount = 0;
                _deviceId = Settings.Secure.GetString(_service.ContentResolver, Settings.Secure.AndroidId);

                // must initialize after _deviceId is set
                if (Insights.IsInitialized)
                    Insights.Identify(_deviceId, "Device ID", _deviceId);
            }
        }
		public Notification Build ()
		{
			Log.Debug (TAG, "Building notification - " + this.ToString ());

			if (mNotificationManager == null) {
				mNotificationManager = (NotificationManager)mContext
					.GetSystemService (Context.NotificationService);
			}

			Bundle extras = new Bundle ();
			if (mBackgroundUri != null) {
				extras.PutString (EXTRA_BACKGROUND_IMAGE_URL, mBackgroundUri);
			}
			var image = Picasso.With (mContext)
				.Load (mImageUri)
				.Resize (Utils.dpToPx (CARD_WIDTH, mContext), Utils.dpToPx (CARD_HEIGHT, mContext))
				.Get ();

			var notification = new NotificationCompat.BigPictureStyle (
				                            new NotificationCompat.Builder (mContext)
				.SetContentTitle (mTitle)
				.SetContentText (mDescription)
				.SetPriority (mPriority)
				.SetLocalOnly (true)
				.SetOngoing (true)
				                            //.SetColor(mContext.Resources.GetColor(Resource.Color.fastlane_background)) FIXME no binding
				                            //.SetCategory(Notification.CATEGORY_RECOMMENDATION) Commented out in example
				                            //.SetCategory("recommendation") FIXME no binding
				.SetLargeIcon (image)
				.SetSmallIcon (mSmallIcon)
				.SetContentIntent (mIntent)
				.SetExtras (extras)).Build ();
			mNotificationManager.Notify (mId, notification);
			mNotificationManager = null;
			return notification;

		}
Example #32
0
        private bool ClearNotifications()
        {
            // Notification Manager
            _notificationManager = (NotificationManager)GetSystemService(NotificationService);

            _notificationManager.Cancel(NotifyPassword);
            _notificationManager.Cancel(NotifyUsername);
            _notificationManager.Cancel(NotifyKeyboard);
            _notificationManager.Cancel(NotifyCombined);
            _numElementsToWaitFor = 0;
            bool hadKeyboardData = ClearKeyboard(false); //do not broadcast if the keyboard was changed
            return hadKeyboardData;
        }
Example #33
0
 public PasswordAccessNotificationBuilder(Context ctx, NotificationManager notificationManager)
 {
     _ctx = ctx;
     _notificationManager = notificationManager;
 }
 private void Notify()
 {
     Log.Debug(logTag, "GpsService.Notify called");
     gpsNotifyManager = (NotificationManager)GetSystemService(Context.NotificationService);
     ShowNotification();
 }
Example #35
0
            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;
            }
        public void NotifyOtherVersions(Context context, Android.Content.Res.Resources res, Android.App.NotificationManager manager)
        {
            Intent intent = new Intent(context, typeof(MainActivity));

            intent.AddFlags(ActivityFlags.SingleTop);
            PendingIntent pendingIntent = PendingIntent.GetActivity(context, 0, intent, PendingIntentFlags.CancelCurrent);
            var           path          = Android.Net.Uri.Parse("android.resource://com.ufinix.uberdriver/" + Resource.Raw.alert);


            Notification.Builder builder = new Notification.Builder(context)
                                           .SetContentTitle("Uber Driver")
                                           .SetSmallIcon(Resource.Drawable.ic_location)
                                           .SetLargeIcon(BitmapFactory.DecodeResource(res, Resource.Drawable.iconimage))
                                           .SetTicker("You have a new trip request")
                                           .SetChannelId(PRIMARY_CHANNEL)
                                           .SetSound(path)
                                           .SetAutoCancel(true)
                                           .SetContentIntent(pendingIntent);

            manager.Notify(NOTIFY_ID, builder.Build());
        }
        public void NotifyVersion26(Context context, Android.Content.Res.Resources res, Android.App.NotificationManager manager)
        {
            string channelName = "Secondary Channel";
            var    importance  = NotificationImportance.High;
            var    channel     = new NotificationChannel(PRIMARY_CHANNEL, channelName, importance);

            var path           = Android.Net.Uri.Parse("android.resource://com.ufinix.uberdriver/" + Resource.Raw.alert);
            var audioattribute = new AudioAttributes.Builder()
                                 .SetContentType(AudioContentType.Sonification)
                                 .SetUsage(AudioUsageKind.Notification).Build();

            channel.EnableLights(true);
            channel.EnableLights(true);
            channel.SetSound(path, audioattribute);
            channel.LockscreenVisibility = NotificationVisibility.Public;

            manager.CreateNotificationChannel(channel);

            Intent intent = new Intent(context, typeof(MainActivity));

            intent.AddFlags(ActivityFlags.SingleTop);
            PendingIntent pendingIntent = PendingIntent.GetActivity(context, 0, intent, PendingIntentFlags.CancelCurrent);

            Notification.Builder builder = new Notification.Builder(context)
                                           .SetContentTitle("Uber Driver")
                                           .SetSmallIcon(Resource.Drawable.ic_location)
                                           .SetLargeIcon(BitmapFactory.DecodeResource(res, Resource.Drawable.iconimage))
                                           .SetContentText("You have a new trip request")
                                           .SetChannelId(PRIMARY_CHANNEL)
                                           .SetAutoCancel(true)
                                           .SetContentIntent(pendingIntent);

            manager.Notify(NOTIFY_ID, builder.Build());
        }
		/**
	     * Cancels an old countdown and deletes the dataItem.
	     *
	     * @param notifyMgr the notification manager.
	     */
		private void CancelCountdown (NotificationManager notifyManager)
		{
			notifyManager.Cancel (Constants.NOTIFICATION_TIMER_EXPIRED);
		}
 public void SetService(AndroidSensusService service)
 {
     _service = service;
     _connectivityManager = _service.GetSystemService(Context.ConnectivityService) as ConnectivityManager;
     _notificationManager = _service.GetSystemService(Context.NotificationService) as NotificationManager;
     _deviceId = Settings.Secure.GetString(_service.ContentResolver, Settings.Secure.AndroidId);
     _textToSpeech = new AndroidTextToSpeech(_service);
     _wakeLock = (_service.GetSystemService(Context.PowerService) as PowerManager).NewWakeLock(WakeLockFlags.Partial, "SENSUS");
 }
        public override void OnCreate()
        {
            Log.Info("LMService.OnCreate", string.Format("In OnCreate"));
            base.OnCreate();

            _repository = new Repository<GeographicData>(this);

            _sbr = new ServiceBroadcastReceiver();
            _sbr.ReceiveMessage += (context, intent) =>
                                       {
                                           var cType = (AppConstants.ServiceCommandType) intent.GetIntExtra(AppConstants.COMMAND_TYPE_ID, -1);
                                           switch (cType)
                                           {
                                               case AppConstants.ServiceCommandType.SendPing:
                                                   {
                                                       Log.Info("TestService", "Ping received");
                                                       var pongIntent = new Intent(AppConstants.APPLICATION_COMMAND);
                                                       pongIntent.PutExtra(AppConstants.COMMAND_TYPE_ID, (int)AppConstants.ApplicationCommandType.ReceivePong);
                                                       Log.Info("TestService", "Sending pong!");
                                                       SendBroadcast(pongIntent);
                                                       break;
                                                   }
                                               case AppConstants.ServiceCommandType.StopService:
                                                   {
                                                       Log.Info("TestService", "Service stopping...");
                                                       ExportData();
                                                       StopSelf();
                                                       break;
                                                   }
                                               case AppConstants.ServiceCommandType.ExportData:
                                                   {
                                                       ExportData();
                                                       break;
                                                   }
                                               default:
                                                   {
                                                       Log.Info("TestService", "Unknown Command: {0}", cType.ToString());
                                                       break;
                                                   }
                                           }
                                       };

            _notificationManager = (NotificationManager) GetSystemService(Context.NotificationService);
            ShowNotification();
            var criteria = new Criteria
                               {
                                   Accuracy = Accuracy.Fine,
                                   PowerRequirement = Power.Medium,
                                   AltitudeRequired = false,
                                   BearingRequired = false,
                                   SpeedRequired = false,
                                   CostAllowed = false,
                               };
            _locationManager = (LocationManager) GetSystemService(Context.LocationService);

            // !!! Remember to enable the location permissions in the project attributes or _bestProvider comes back null :)
            // you will also need to ensure that the container class either inherits from Service or Activity, or it goes all crashy;
            // but you'll see a build warning about it implementing IJavaObject but not inheriting from Java.Object
            _bestProvider = _locationManager.GetBestProvider(criteria, false);
            // Location _location = _locationManager.GetLastKnownLocation(_bestProvider);
            // at least 15 seconds between updates, at least 100 metres between updates, 'this' because it implements ILocationListener.
            _locationManager.RequestLocationUpdates(_bestProvider, 15000, 100, this);
        }