void SetNotificationPlaybackState(Notification.Builder builder)
        {
            var beginningOfTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

            LogHelper.Debug(Tag, "updateNotificationPlaybackState. mPlaybackState=" + playbackState);
            if (playbackState == null || !started)
            {
                LogHelper.Debug(Tag, "updateNotificationPlaybackState. cancelling notification!");
                service.StopForeground(true);
                return;
            }
            if (playbackState.State == PlaybackStateCode.Playing &&
                playbackState.Position >= 0)
            {
                var timespan = ((long)(DateTime.UtcNow - beginningOfTime).TotalMilliseconds) - playbackState.Position;
                LogHelper.Debug(Tag, "updateNotificationPlaybackState. updating playback position to ", timespan / 1000, " seconds");

                builder.SetWhen(timespan).SetShowWhen(true).SetUsesChronometer(true);
            }
            else
            {
                LogHelper.Debug(Tag, "updateNotificationPlaybackState. hiding playback position");
                builder.SetWhen(0).SetShowWhen(false).SetUsesChronometer(false);
            }

            // Make sure that the notification can be dismissed by the user when we are not playing:
            builder.SetOngoing(playbackState.State == PlaybackStateCode.Playing);
        }
        public void ShowLocalNotification(string title, string text, DateTime time)
        {
            //Se comenta esta parte mientras se define que pantalla mostrar cuando se abre la notificación.
            //// Set up an intent so that tapping the notifications returns to this app:
            //Intent intent = new Intent(Application.Context, typeof(MainActivity));

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



            // Instantiate the builder and set notification elements:
            Notification.Builder builder = new Notification.Builder(Application.Context)
                                           .SetContentTitle(title).SetContentText(text)
                                           .SetSmallIcon(Resource.Drawable.icon);
            //.SetContentIntent(pendingIntent);

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

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

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

            notificationManager.Notify(notificationId, notification);

            builder.SetWhen(time.Millisecond);
        }
示例#3
0
        public void SendNotification(string title, string text, bool sound = false, bool progress = false, int total = 0, int partial = 0, int percentMax = 100)
        {
            // Instantiate the builder and set notification elements:
            Notification.Builder builder = new Notification.Builder(Application.Context)
                                           .SetContentTitle(title).SetContentText(text)
                                           .SetSmallIcon(Resource.Drawable.icon);//.SetTicker("");

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

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

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

            if (progress)
            {
                builder.SetProgress(percentMax, percentMax * partial / total, false);
            }

            if (sound)
            {
                builder.SetSound(Android.Media.RingtoneManager.GetDefaultUri(Android.Media.RingtoneType.Notification));
            }

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

            builder.SetWhen(DateTime.Now.Millisecond);
        }
        private void Button_Click(object sender, EventArgs e)
        {
            notyBuilder = new Notification.Builder(this);

            notyBuilder.SetContentTitle("عنوان پیام");
            notyBuilder.SetContentText("متن پیام در اینجا قرار میگیرد");
            notyBuilder.SetSmallIcon(Resource.Drawable.noty_small_icon);
            notyBuilder.SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.noty_large_icon));
            notyBuilder.SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis());
            notyBuilder.SetDefaults(NotificationDefaults.Sound | NotificationDefaults.Vibrate);
            notyBuilder.SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification));
            notyBuilder.SetAutoCancel(true);
            notyBuilder.SetPriority((int)NotificationPriority.High);

            if ((int)Android.OS.Build.VERSION.SdkInt >= 21)
            {
                notyBuilder.SetVisibility(NotificationVisibility.Public);
                notyBuilder.SetCategory(Notification.CategoryEmail);
            }



            #region BigTextStyle

            Notification.BigTextStyle textStyle = new Notification.BigTextStyle();
            string longTextMessage = "I went up one pair of stairs.";
            longTextMessage += " / Just like me. ";
            textStyle.BigText(longTextMessage);
            textStyle.SetSummaryText("The summary text goes here.");
            //notyBuilder.SetStyle(textStyle);

            #endregion

            #region InboxStyle

            var inboxStyle = new Notification.InboxStyle();
            inboxStyle.AddLine("Cheeta: Bananas on sale");
            inboxStyle.AddLine("George: Curious about your blog post");
            inboxStyle.AddLine("Nikko: Need a ride to Evolve?");
            inboxStyle.SetSummaryText("+2 more");

            notyBuilder.SetStyle(inboxStyle);

            #endregion

            #region imageStyle

            var imageStyle = new Notification.BigPictureStyle();
            imageStyle.BigPicture(BitmapFactory.DecodeResource(Resources, Resource.Drawable.facebook));
            imageStyle.SetSummaryText("+2 more");
            //notyBuilder.SetStyle(imageStyle);


            #endregion

            var notification = notyBuilder.Build();
            var notyManager  = GetSystemService(Context.NotificationService) as NotificationManager;
            notyManager.Notify(notyId, notification);
        }
示例#5
0
        private async void Current_ConnectivityChanged(object sender, Plugin.Connectivity.Abstractions.ConnectivityChangedEventArgs e)
        {
            // Get the notification manager:
            NotificationManager notificationManager =
                GetSystemService(Context.NotificationService) as NotificationManager;

            Notification.Builder builder1      = new Notification.Builder(this);
            Notification         notification1 = builder1.Build();


            if (e.IsConnected)
            {
                var eValue = App.DAUtil.GetAll <OfflineItem>("OfflineItem");
                if (eValue.Count > 0)
                {
                    var intent = new Intent(this, typeof(MainActivity));
                    intent.AddFlags(ActivityFlags.ClearTop);
                    var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);

                    builder1.SetContentTitle("Nokcoot");
                    builder1.SetContentText("Offline drafts uploaded");
                    builder1.SetAutoCancel(true);
                    builder1.SetDefaults(NotificationDefaults.Sound);

                    builder1.SetSmallIcon(Resource.Drawable.logo);
                    builder1.SetContentIntent(pendingIntent);
                    builder1.SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis());
                    notification1           = builder1.Build();
                    notification1.Defaults |= NotificationDefaults.Vibrate;
                    await OAuthHelper.SyncOfflineItems();
                }

                MessagingCenter.Subscribe <object, string>(this, "notify", (s, e1) =>
                {
                    Device.BeginInvokeOnMainThread(() =>
                    {
                        if (App.DAUtil.GetAll <OfflineItem>("OfflineItem").Count == 0)
                        {
                            notificationManager.Notify(SERVICE_RUNNING_NOTIFICATION_ID1, notification1);
                            StopForeground(true);
                        }
                    });
                });

                //  notification.SetDefaults(NotificationDefaults.Sound | NotificationDefaults.Vibrate);
            }
        }
示例#6
0
    public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
    {
        new Task(() => {
            PendingIntent pIntent        = PendingIntent.GetActivity(this, 0, intent, 0);
            Notification.Builder builder = new Notification.Builder(this);
            builder.SetContentTitle("hello");
            builder.SetContentText("hello");
            builder.SetSmallIcon(Resource.Drawable.Icon);
            builder.SetPriority(1);
            builder.SetDefaults(NotificationDefaults.Sound | NotificationDefaults.Vibrate);
            builder.SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis());
            Notification notifikace = builder.Build();
            NotificationManager notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
            const int notificationId = 0;
            notificationManager.Notify(notificationId, notifikace);
        }).Start();

        return(StartCommandResult.Sticky);
    }
示例#7
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // 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 += (object sender, System.EventArgs e) =>
            {
                // Instantiate the builder and set notification elements:
                Notification.Builder builder = new Notification.Builder(this)
                                               .SetContentTitle("Xin chao cac ban!! Hello")
                                               .SetContentText("Hello World! This is my first notification!")
                                               .SetSmallIcon(Resource.Drawable.Alarm);
                //The timestamp is set automatically, but you can override this setting by calling the SetWhen method of the notification builder.
                //For example, the following code example sets the timestamp to the current time:
                builder.SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis());

                /*
                 * This call to SetDefaults will cause the device to play a sound when the notification is published.
                 * If you want the device to vibrate rather than play a sound, you can pass NotificationDefaults.Vibrate to SetDefaults.
                 * If you want the device to play a sound and vibrate the device, you can pass both flags to SetDefaults:
                 */
                builder.SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Ringtone));

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

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

                // Publish the notification:
                const int notificationId = 0;
                notificationManager.Notify(notificationId, notification);
            };;
        }
        public override void OnReceive(Context context, Intent intent)
        {
            Intent secondIntent = new Intent(context, typeof(RemedioActivity));

            // Pass some information to SecondActivity:
            secondIntent.PutExtra("message", "Greetings from MainActivity!");

            // 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(RemedioActivity)));

            // 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);

            Notification.Builder builder = new Notification.Builder(context).
                                           SetContentTitle("Notificação remédio").
                                           SetContentIntent(pendingIntent).
                                           SetContentText("Lmebre-se de tomar o remédio")
                                           .SetSmallIcon(Resource.Drawable.Icon);

            builder.SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis());

            Notification        notification        = builder.Build();
            NotificationManager notificationManager = context.GetSystemService(Context.NotificationService) as NotificationManager;

            notificationManager.Notify(0, notification);
            //Toast.MakeText(context, "Alarme", ToastLength.Short).Show();
        }/*
        private void CreateBuilder()
        {
            var builder = new Notification.Builder(Application.Context, channelId);

            builder.SetChannelId(channelId);

            //Configure builder
            builder.SetContentTitle("track title goes here");
            builder.SetContentText("artist goes here");
            builder.SetWhen(0);

            //TODO: set if the notification can be destroyed by swiping
            //if (infos.dismissable)
            //{
            //	builder.setOngoing(false);
            //	Intent dismissIntent = new Intent("music-controls-destroy");
            //	PendingIntent dismissPendingIntent = PendingIntent.getBroadcast(context, 1, dismissIntent, 0);
            //	builder.setDeleteIntent(dismissPendingIntent);
            //}
            //else
            //{
            //	builder.setOngoing(true);
            //}
            if (AndroidMediaManager.SharedInstance.IsPlaying)
            {
                builder.SetOngoing(true);
            }
            else
            {
                builder.SetOngoing(false);
            }

            //If 5.0 >= set the controls to be visible on lockscreen
            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop)
            {
                builder.SetVisibility(NotificationVisibility.Public);
            }

            //Set SmallIcon (Notification Icon in top bar)
            builder.SetSmallIcon(Android.Resource.Drawable.IcMediaPlay);

            //TODO: Set LargeIcon
            // builder.SetLargeIcon(AlbumArt.jpg);

            //TODO: Open app if tapped
            //Intent resultIntent = new Intent(context, typeof(Application));
            //resultIntent.SetAction(Intent.ActionMain);
            //resultIntent.AddCategory(Intent.CategoryLauncher);
            //PendingIntent resultPendingIntent = PendingIntent.GetActivity(context, 0, resultIntent, 0);
            //builder.SetContentIntent(resultPendingIntent);

            //Controls
            var controlsCount = 0;

            /* Previous  */
            controlsCount++;
            builder.AddAction(previousAction);

            /* Play/Pause */
            if (AndroidMediaManager.SharedInstance.IsPlaying)
            {
                controlsCount++;
                builder.AddAction(pauseAction);
            }
            else
            {
                controlsCount++;
                builder.AddAction(playAction);
            }

            /* Next */
            controlsCount++;
            builder.AddAction(nextAction);

            /* Close */
            //controlsCount++;
            //builder.AddAction(destroyAction);

            //If 5.0 >= use MediaStyle
            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop)
            {
                int[] args = new int[controlsCount];
                for (int i = 0; i < controlsCount; ++i)
                {
                    args[i] = i;
                }
                var style = new Notification.MediaStyle();
                style.SetShowActionsInCompactView(args);
                builder.SetStyle(style);
            }

            this.notificationBuilder = builder;
        }
        private void CreateBuilder(IMediaItem mediaItem)
        {
            var builder = new Notification.Builder(Application.Context, channelId);

            builder.SetChannelId(channelId);

            //Configure builder
            builder.SetContentTitle(mediaItem.Title);
            builder.SetContentText(mediaItem.Artist);
            builder.SetWhen(0);

            if (AndroidAudioPlayer.SharedInstance.IsPlaying)
            {
                builder.SetOngoing(true);
                builder.SetSmallIcon(Android.Resource.Drawable.IcMediaPlay);
            }
            else
            {
                builder.SetOngoing(false);
                Intent        dismissIntent        = new Intent(ButtonEvents.AudioControlsDestroy);
                PendingIntent dismissPendingIntent = PendingIntent.GetBroadcast(Application.Context, 1, dismissIntent, 0);
                builder.SetDeleteIntent(dismissPendingIntent);
                builder.SetSmallIcon(Android.Resource.Drawable.IcMediaPause);
            }

            //If 5.0 >= set the controls to be visible on lockscreen
            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop)
            {
                builder.SetVisibility(NotificationVisibility.Public);
            }

            if (!string.IsNullOrWhiteSpace(mediaItem.AlbumArtUrl))
            {
                try
                {
                    var bitmap = new AsyncImageDownloader().Execute(new string[] { mediaItem.AlbumArtUrl });
                    builder.SetLargeIcon(bitmap.GetResult());
                }
                catch (Java.Lang.Exception exc)
                {
                    Console.WriteLine($"Unable to find Album Art URL for {mediaItem.AlbumArtUrl}");
                    Console.WriteLine(exc.ToString());
                }
            }

            Intent resultIntent = new Intent(Application.Context, typeof(Activity));

            resultIntent.SetAction(Intent.ActionMain);
            resultIntent.AddCategory(Intent.CategoryLauncher);
            PendingIntent resultPendingIntent = PendingIntent.GetActivity(Application.Context, 0, resultIntent, PendingIntentFlags.UpdateCurrent);

            builder.SetContentIntent(resultPendingIntent);

            //Controls
            var controlsCount = 0;

            // Previous
            controlsCount++;
            builder.AddAction(previousAction);

            // Play/Pause
            builder.AddAction(pauseAction);

            // Next
            controlsCount++;
            builder.AddAction(nextAction);

            // Close
            //controlsCount++;
            //builder.AddAction(destroyAction);

            // If 5.0 >= use MediaStyle
            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop)
            {
                int[] args = new int[controlsCount];
                for (int i = 0; i < controlsCount; ++i)
                {
                    args[i] = i;
                }
                var style = new Notification.MediaStyle();
                style.SetShowActionsInCompactView(args);
                builder.SetStyle(style);
            }
            notificationBuilder = builder;
        }
示例#11
0
        public static async void ShowLocalNot(LocalNot not, Context context = null)
        {
            var cc      = context ?? Application.Context;
            var builder = new Notification.Builder(cc);

            builder.SetContentTitle(not.title);

            bool containsMultiLine = not.body.Contains("\n");

            if (Build.VERSION.SdkInt < BuildVersionCodes.O || !containsMultiLine)
            {
                builder.SetContentText(not.body);
            }
            builder.SetSmallIcon(not.smallIcon);
            builder.SetAutoCancel(not.autoCancel);
            builder.SetOngoing(not.onGoing);

            if (not.progress != -1)
            {
                builder.SetProgress(100, not.progress, false);
            }

            builder.SetVisibility(NotificationVisibility.Public);
            builder.SetOnlyAlertOnce(true);

            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                var channelId = $"{cc.PackageName}.general";
                var channel   = new NotificationChannel(channelId, "General", (NotificationImportance)not.notificationImportance);
                NotManager.CreateNotificationChannel(channel);

                builder.SetChannelId(channelId);

                if (not.bigIcon != null)
                {
                    if (not.bigIcon != "")
                    {
                        var bitmap = await GetImageBitmapFromUrl(not.bigIcon);

                        if (bitmap != null)
                        {
                            builder.SetLargeIcon(bitmap);
                            if (not.mediaStyle)
                            {
                                builder.SetStyle(new Notification.MediaStyle());                                 // NICER IMAGE
                            }
                        }
                    }
                }

                if (containsMultiLine)
                {
                    var b = new Notification.BigTextStyle();
                    b.BigText(not.body);
                    builder.SetStyle(b);
                }

                if (not.actions.Count > 0)
                {
                    List <Notification.Action> actions = new List <Notification.Action>();

                    for (int i = 0; i < not.actions.Count; i++)
                    {
                        var _resultIntent = new Intent(context, typeof(MainIntentService));
                        _resultIntent.PutExtra("data", not.actions[i].action);
                        var pending = PendingIntent.GetService(context, 3337 + i + not.id,
                                                               _resultIntent,
                                                               PendingIntentFlags.UpdateCurrent
                                                               );
                        actions.Add(new Notification.Action(not.actions[i].sprite, not.actions[i].name, pending));
                    }

                    builder.SetActions(actions.ToArray());
                }
            }

            builder.SetShowWhen(not.showWhen);
            if (not.when != null)
            {
                builder.SetWhen(CurrentTimeMillis((DateTime)not.when));
            }
            var stackBuilder = Android.Support.V4.App.TaskStackBuilder.Create(cc);

            var resultIntent = GetLauncherActivity(cc);

            if (not.data != "")
            {
                resultIntent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);
                var _data = Android.Net.Uri.Parse(not.data);                //"cloudstreamforms:tt0371746Name=Iron man=EndAll");
                resultIntent.SetData(_data);
                stackBuilder.AddNextIntent(resultIntent);
                var resultPendingIntent =
                    stackBuilder.GetPendingIntent(not.id, (int)PendingIntentFlags.UpdateCurrent);
                builder.SetContentIntent(resultPendingIntent);
            }
            else
            {
                stackBuilder.AddNextIntent(resultIntent);

                builder.SetContentIntent(GetCurrentPending());
            }

            try {
                NotManager.Notify(not.id, builder.Build());
            }
            catch { }
        }
示例#12
0
        protected override void OnHandleIntent(Intent intent)
        {
            if (running)
            {
                return;
            }
            running = true;

            meetingReceiver = new MeetingReceiver();
            IntentFilter intentFilter = new IntentFilter(ActionNewMeeting);

            RegisterReceiver(meetingReceiver, intentFilter);

            Task <Core.Common.Result <IList <Meeting> > > task = eventService.FetchLatestEvent();

            while (running)
            {
                if (task.IsCompleted || task.IsCanceled || task.IsFaulted)
                {
                    if (task.IsCompleted)
                    {
                        if (!task.Result.HasError)
                        {
                            var newMeetings = task.Result.Model
                                              .Where((meeting) => { return(meeting.MeetingCreatedAt > ServiceContext.Instance.LatestMeetingTime); })
                                              .ToList();
                            if (newMeetings.Count != 0)
                            {
                                newMeetings.Sort((x, y) =>
                                {
                                    if (x.MeetingCreatedAt > y.MeetingCreatedAt)
                                    {
                                        return(-1);
                                    }
                                    else if (x.MeetingCreatedAt == y.MeetingCreatedAt)
                                    {
                                        return(0);
                                    }
                                    else
                                    {
                                        return(1);
                                    }
                                });
                                ServiceContext.Instance.LatestMeetingTime = newMeetings[0].MeetingCreatedAt;
                                StringBuilder strBuilder = new StringBuilder();
                                for (int i = 0; i < newMeetings.Count; i++)
                                {
                                    strBuilder.Append(newMeetings[i].MeetingName);
                                    if (i != newMeetings.Count - 1)
                                    {
                                        strBuilder.Append("\n");
                                    }
                                }

                                Notification.Builder builder = new Notification.Builder(this);
                                builder.SetSmallIcon(Resource.Drawable.icon);
                                builder.SetTicker($"{newMeetings.Count}条新会议\n");
                                builder.SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis());
                                builder.SetContentTitle("新的会议");
                                builder.SetContentText(strBuilder.ToString());

                                Intent        intent1       = new Intent(ActionNewMeeting);
                                PendingIntent pendingIntent = PendingIntent.GetBroadcast(this, 0, intent1, PendingIntentFlags.CancelCurrent);
                                builder.SetContentIntent(pendingIntent);//设置点击过后跳转的activity

                                /*builder.setDefaults(Notification.DEFAULT_SOUND);//设置声音
                                 * builder.setDefaults(Notification.DEFAULT_LIGHTS);//设置指示灯
                                 * builder.setDefaults(Notification.DEFAULT_VIBRATE);//设置震动*/
                                builder.SetDefaults(NotificationDefaults.All);      //设置全部

                                Notification notification = builder.Build();        //4.1以上用.build();
                                notification.Flags |= NotificationFlags.AutoCancel; // 点击通知的时候cancel掉
                                NotificationManager manager = (NotificationManager)GetSystemService(NotificationService);
                                manager.Notify(1, notification);

                                MessagingCenter.Send(Xamarin.Forms.Application.Current, "NewMeeting");
                            }
                        }
                        try
                        {
                            Thread.Sleep(3000);
                        }
                        catch (InterruptedException) {}
                    }
                    task = eventService.FetchLatestEvent();
                }
            }
        }
示例#13
0
        private void startMyService()
        {
            //create the default activity to be shown
            Intent        intent  = new Intent();
            PendingIntent pending = PendingIntent.GetActivity(this, 0, intent, 0);


            if (Android.OS.Build.VERSION.SdkInt <= BuildVersionCodes.NMr1)
            {
                var notification = new Notification.Builder(this, Constants.CHANNEL_ID)
                                   .SetContentTitle(Constants.CONTENT_TITLE)
                                   .SetContentText(Constants.CONTENT_TEXT)
                                   .SetSmallIcon(Resource.Drawable.bsplash)
                                   .SetOngoing(true)
                                   .Build();

                StartForeground(300, notification);
            }

            else
            {
                //create a notification channel. this is a must if your service is going to run on
                //Android 8.0(Oreo) and above
                NotificationChannel channel = new NotificationChannel(MPConstants.CHANNEL_ID1, MPConstants.CHANNEL_NAME, NotificationImportance.Default);
                NotificationManager manager = GetSystemService(NotificationService) as NotificationManager;

                if (manager != null)
                {
                    manager.CreateNotificationChannel(channel);
                }

                //create the notification
                var builder = new Notification.Builder(this, MPConstants.CHANNEL_ID1);

                //make notification show big text
                Notification.BigTextStyle BigStyle = new Notification.BigTextStyle();
                BigStyle.SetBigContentTitle("This service is running in the foreground");
                BigStyle.BigText("This is a music like foreground service that was built using some tutorial and some little tweaks");
                builder.SetStyle(BigStyle);

                //build notification
                builder.SetWhen(DateTime.Now.Millisecond);
                builder.SetSmallIcon(Resource.Drawable.badge);
                //////set large icon of type Bitmap
                //Bitmap LargeIconBitMap = BitmapFactory.DecodeResource(Resources.get, Resource.Drawable.bsplash);

                //used to set full screen intent
                builder.SetFullScreenIntent(pending, true);

                //Add play button to Notification
                Intent PlayIntent = new Intent(this, typeof(MusicService));
                intent.SetAction(MPConstants.ACTION_PLAY);
                PendingIntent       PendingPlayIntent = PendingIntent.GetService(this, 0, PlayIntent, 0);
                Notification.Action playaction        = new Notification.Action(Resource.Drawable.ic_media_play_light, "Play", PendingPlayIntent);
                builder.AddAction(playaction);

                //add Pause button to Notification
                Intent PauseIntent = new Intent(this, typeof(MusicService));
                intent.SetAction(MPConstants.ACTION_PAUSE);
                PendingIntent       PausePendingIntent = PendingIntent.GetService(this, 0, PauseIntent, 0);
                Notification.Action PauseAction        = new Notification.Action(Resource.Drawable.ic_media_pause_light, "Pause", PausePendingIntent);
                builder.AddAction(PauseAction);

                //build notification
                Notification notification = builder.Build();

                StartForeground(500, notification);
            }
        }
示例#14
0
        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            base.OnStartCommand(intent, flags, startId);

            var notificationIntent = new Intent(BaseContext, typeof(MainActivity));
            notificationIntent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop);
            var notifPendingIntent = PendingIntent.GetActivity(BaseContext, 0, notificationIntent, PendingIntentFlags.UpdateCurrent);
            var notif = new Notification
            {
                ContentIntent = notifPendingIntent
            };

            Notification.Builder notifBuilder = new Notification.Builder(BaseContext);
            notifBuilder.SetContentIntent(notifPendingIntent);
            notifBuilder.SetWhen(JavaSystem.CurrentTimeMillis());
            notifBuilder.SetSmallIcon(Resource.Drawable.Knock);
            notifBuilder.SetContentTitle(Resources.GetString(Resource.String.ApplicationName));
            notifBuilder.SetContentText(Resources.GetString(Resource.String.NotifText));

            StartForeground(Process.MyPid(), notifBuilder.Build());
            
            //var notificationManager = (NotificationManager) BaseContext.GetSystemService(NotificationService);
            //notificationManager.Notify(Process.MyPid(), new Notification { ContentIntent = notifPendingIntent });

            RegisterListener();

            _wakeLockPartial?.Acquire();

            Status = ServiceStatus.STARTED;
            Log.Debug("WakeUpService", "Service start command.");
            return StartCommandResult.StickyCompatibility;
        }