Example #1
0
        /// <summary>
        /// Updates the state of the player.
        /// </summary>
        /// <param name="state">The state.</param>
        /// <param name="position"></param>
        public void UpdatePlaybackState(int state, int position = 0)
        {
            if (CurrentSession == null && (_binder?.IsBinderAlive).GetValueOrDefault(false) && !string.IsNullOrWhiteSpace(_packageName))
            {
                InitMediaSession(_packageName, _binder);
            }

            PlaybackStateCompat.Builder stateBuilder = new PlaybackStateCompat.Builder()
                                                       .SetActions(PlaybackStateCompat.ActionPlay
                                                                   | PlaybackStateCompat.ActionPlayPause
                                                                   | PlaybackStateCompat.ActionPause
                                                                   | PlaybackStateCompat.ActionSkipToNext
                                                                   | PlaybackStateCompat.ActionSkipToPrevious
                                                                   | PlaybackStateCompat.ActionStop);

            stateBuilder.SetState(state, position, 0, SystemClock.ElapsedRealtime());
            CurrentSession?.SetPlaybackState(stateBuilder.Build());
            OnStatusChanged?.Invoke(CurrentSession, state);

            //Used for backwards compatibility
            if ((Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop) &&
                (CurrentSession?.RemoteControlClient == null ||
                 (bool)!CurrentSession?.RemoteControlClient.Equals(typeof(RemoteControlClient))))
            {
                return;
            }

            RemoteControlClient remoteControlClient = (RemoteControlClient)CurrentSession?.RemoteControlClient;

            RemoteControlFlags flags = RemoteControlFlags.Play
                                       | RemoteControlFlags.Pause
                                       | RemoteControlFlags.PlayPause;

            remoteControlClient?.SetTransportControlFlags(flags);
        }
Example #2
0
        public override void OnCreate()
        {
            base.OnCreate();

            // Create a MediaSessionCompat
            mMediaSession = new MediaSessionCompat(ApplicationContext, LogTag);

            // Enable callbacks from MediaButtons and TransportControls
            mMediaSession.SetFlags(
                MediaSessionCompat.FlagHandlesMediaButtons |
                MediaSessionCompat.FlagHandlesTransportControls);

            // Set an initial PlaybackState with ACTION_PLAY, so media buttons can start the player
            mStateBuilder = new PlaybackStateCompat.Builder()
                            .SetActions(
                PlaybackStateCompat.ActionPlay |
                PlaybackStateCompat.ActionPause);

            mMediaSession.SetPlaybackState(mStateBuilder.Build());

            // MySessionCallback() has methods that handle callbacks from a media controller
            mMediaSession.SetCallback(new MySessionCallback());

            // Set the session's token so that client activities can communicate with it.
            SessionToken = mMediaSession.SessionToken;
        }
Example #3
0
        void UpdateSession()
        {
            var stateBuilder = new PlaybackStateCompat.Builder().SetActions(AvailableActions);



            Console.WriteLine("************");
            Console.WriteLine("***************");
            Console.WriteLine($"Media player: Playback State: {StateIsPlaying}/{IsPlaying} - position {Position}");
            Console.WriteLine("***************");
            Console.WriteLine("******");

            var favIcon            = Parent.CurrentSong?.Rating > 1 ? Resource.Drawable.ic_star_on : Resource.Drawable.ic_star_off;
            var customActionExtras = new Bundle();

            //TODO: run through wearables
            stateBuilder.AddCustomAction(
                new PlaybackStateCompat.CustomAction.Builder("THUMBSUP", "FAVORITE", favIcon).SetExtras(customActionExtras).Build());
            stateBuilder.SetState(State, Position, 1f, SystemClock.ElapsedRealtime());

            MusicService.Shared.Session.SetPlaybackState(stateBuilder.Build());

            if (State == PlaybackStateCompat.StatePlaying || State == PlaybackStateCompat.StatePaused)
            {
                MusicService.Shared.MediaNotificationManager.StartNotification();
            }
        }
        private void UpdatePlaybackState(int state)
        {
            if (_mediaSessionCompat != null && _player != null)
            {
                try
                {
                    PlaybackStateCompat.Builder stateBuilder = new PlaybackStateCompat.Builder()
                                                               .SetActions(
                        PlaybackStateCompat.ActionPause |
                        PlaybackStateCompat.ActionPlay |
                        PlaybackStateCompat.ActionPlayPause |
                        PlaybackStateCompat.ActionSkipToNext |
                        PlaybackStateCompat.ActionSkipToPrevious |
                        PlaybackStateCompat.ActionStop
                        )
                                                               .SetState(state, (long)_player?.CurrentPosition, 1.0f, SystemClock.ElapsedRealtime());
                    _mediaSessionCompat.SetPlaybackState(stateBuilder.Build());

                    if (state == PlaybackStateCompat.StatePlaying || state == PlaybackStateCompat.StatePaused)
                    {
                        StartNotification();
                    }
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(e);
                }
            }
        }
Example #5
0
        public PlatformAudioPlayer(Context _context)
        {
            // Assign Activity context and stuff
            this.context = _context;
            this.tracks  = new Track[] { null, null, null, null };

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

            // Give the media session some capabilities, including the ability to be controlled by Media Buttons
            PlaybackStateCompat.Builder playbackState = new PlaybackStateCompat.Builder().SetActions(PlaybackStateCompat.ActionPlay | PlaybackStateCompat.ActionPlayPause);
            NotificationCompat.Builder  notiBuilder   = new NotificationCompat.Builder(this.context);
            notiBuilder.SetOngoing(true);
            notiBuilder.SetSmallIcon(Resource.Drawable.icon);
            notiBuilder.SetContentTitle("Metronome Amplified");
            notiBuilder.SetContentText("Control");

            // Make a pending intent to focus the app
            Intent        intent = new Intent(this.context, typeof(MainActivity));
            PendingIntent pend   = PendingIntent.GetActivity(this.context, NOTIFICATION_ID, intent, PendingIntentFlags.CancelCurrent);

            notiBuilder.SetContentIntent(pend);

            /*
             * // Make an intent to stop the player
             * Intent stopIntent = new Intent(this.context, typeof(ActionService));
             * PendingIntent stopPending = PendingIntent.GetService(this.context, NOTIFICATION_ID, stopIntent, PendingIntentFlags.CancelCurrent);
             * notiBuilder.AddAction(Resource.Drawable.stopbutton, "Stop", stopPending);
             */
            // Set the amount of visible detail for show on the lock screen (nothing need be private here)
            notiBuilder.SetVisibility(NotificationCompat.VisibilityPublic);

            // Build the notification
            notify = notiBuilder.Build();
        }
Example #6
0
        public void SetPlaybackState(int state, Action <PlaybackStateCompat.Builder> configure = null)
        {
            var builder = new PlaybackStateCompat.Builder()
                          .SetActions(PlaybackStateCompat.ActionPlay | PlaybackStateCompat.ActionStop)
                          .SetState(state, -1, 1.0f, SystemClock.ElapsedRealtime());

            configure?.Invoke(builder);

            _session.SetPlaybackState(builder.Build());
        }
        private void UpdatePlaybackState(int state)
        {
            if (mediaSessionCompat == null || mediaPlayer == null)
            {
                return;
            }

            try
            {
                PlaybackStateCompat.Builder stateBuilder = new PlaybackStateCompat.Builder()
                                                           .SetActions(
                    PlaybackStateCompat.ActionPause |
                    PlaybackStateCompat.ActionPlay |
                    PlaybackStateCompat.ActionPlayPause |
                    PlaybackStateCompat.ActionSkipToNext |
                    PlaybackStateCompat.ActionSkipToPrevious |
                    PlaybackStateCompat.ActionStop
                    )
                                                           .SetState(state, Position, 1.0f, SystemClock.ElapsedRealtime());

                mediaSessionCompat.SetPlaybackState(stateBuilder.Build());

                //Used for backwards compatibility
                if (Build.VERSION.SdkInt < BuildVersionCodes.Lollipop)
                {
                    if (mediaSessionCompat.RemoteControlClient != null && mediaSessionCompat.RemoteControlClient.Equals(typeof(RemoteControlClient)))
                    {
                        RemoteControlClient remoteControlClient = (RemoteControlClient)mediaSessionCompat.RemoteControlClient;

                        RemoteControlFlags flags = RemoteControlFlags.Play
                                                   | RemoteControlFlags.Pause
                                                   | RemoteControlFlags.PlayPause
                                                   | RemoteControlFlags.Previous
                                                   | RemoteControlFlags.Next
                                                   | RemoteControlFlags.Stop;

                        remoteControlClient.SetTransportControlFlags(flags);
                    }
                }

                OnStatusChanged(EventArgs.Empty);

                if (state == PlaybackStateCompat.StatePlaying || state == PlaybackStateCompat.StatePaused)
                {
                    StartNotification();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        public RadioStationMediaSession SetPlaybackState(int state, TimeSpan position = default(TimeSpan), Action <PlaybackStateCompat.Builder> configure = null)
        {
            var positionMS = position == default(TimeSpan) ? -1 : (long)Math.Ceiling(position.TotalMilliseconds);
            var builder    = new PlaybackStateCompat.Builder()
                             .SetActions(PlaybackStateCompat.ActionPlay | PlaybackStateCompat.ActionPause)
                             .SetState(state, positionMS, 1.0f, SystemClock.ElapsedRealtime());

            configure?.Invoke(builder);

            _session.SetPlaybackState(builder.Build());

            return(this);
        }
Example #9
0
        public void UpdatePlaybackState(string error)
        {
            LogHelper.Debug(Tag, "updatePlaybackState, playback state=" + Playback.State);
            long position = PlaybackStateCompat.PlaybackPositionUnknown;

            if (Playback != null && Playback.IsConnected)
            {
                position = Playback.CurrentStreamPosition;
            }

            //noinspection ResourceType
            PlaybackStateCompat.Builder stateBuilder = new PlaybackStateCompat.Builder()
                                                       .SetActions(GetAvailableActions());

            //setCustomAction(stateBuilder);
            int state = Playback.State;

            // If there is an error message, send it to the playback state:
            if (error != null)
            {
                // Error states are really only supposed to be used for errors that cause playback to
                // stop unexpectedly and persist until the user takes action to fix it.
                stateBuilder.SetErrorMessage(error);
                state = PlaybackStateCompat.StateError;
            }
            //noinspection ResourceType
            stateBuilder.SetState(state, position, 1.0f, SystemClock.ElapsedRealtime());

            // Set the activeQueueItemId if the current index is valid.
            MediaSessionCompat.QueueItem currentMusic = queueManager.CurrentMusic;
            if (currentMusic != null)
            {
                stateBuilder.SetActiveQueueItemId(currentMusic.QueueId);
            }

            serviceCallback.OnPlaybackStateUpdated(stateBuilder.Build());

            if (state == PlaybackStateCompat.StatePlaying ||
                state == PlaybackStateCompat.StatePaused)
            {
                serviceCallback.OnNotificationRequired();
            }
        }
Example #10
0
 private void SetMediaPlaybackState(int state)
 {
     PlaybackStateCompat.Builder playbackstateBuilder = new PlaybackStateCompat.Builder();
     if (state == PlaybackStateCompat.StatePlaying)
     {
         playbackstateBuilder.SetActions(PlaybackStateCompat.ActionPlayPause | PlaybackStateCompat.ActionPause | PlaybackStateCompat.ActionSkipToNext | PlaybackStateCompat.ActionSkipToPrevious |
                                         PlaybackStateCompat.ActionPlayFromMediaId |
                                         PlaybackStateCompat.ActionPlayFromSearch | PlaybackStateCompat.ActionPlayFromUri | PlaybackStateCompat.ActionPlay);
         playbackstateBuilder.SetState(state, PlaybackStateCompat.PlaybackPositionUnknown, 1.0f);
     }
     else
     {
         playbackstateBuilder.SetActions(PlaybackStateCompat.ActionPlayPause | PlaybackStateCompat.ActionPlay | PlaybackStateCompat.ActionSkipToNext | PlaybackStateCompat.ActionSkipToPrevious |
                                         PlaybackStateCompat.ActionPlayFromMediaId |
                                         PlaybackStateCompat.ActionPlayFromSearch | PlaybackStateCompat.ActionPlayFromUri | PlaybackStateCompat.ActionPause);
         playbackstateBuilder.SetState(state, PlaybackStateCompat.PlaybackPositionUnknown, 0);
     }
     mediaSessionCompat.SetPlaybackState(playbackstateBuilder.Build());
 }
        /// <summary>
        /// Updates the state of the player.
        /// </summary>
        /// <param name="state">The state.</param>
        /// <param name="position"></param>
        public void UpdatePlaybackState(int state, int position = 0, string errorMessage = "")
        {
            if(CurrentSession == null && (_binder?.IsBinderAlive).GetValueOrDefault(false) && !string.IsNullOrWhiteSpace(_packageName))
                InitMediaSession(_packageName, _binder);

            PlaybackStateCompat.Builder stateBuilder = new PlaybackStateCompat.Builder()
                    .SetActions(PlaybackStateCompat.ActionPlay
                        | PlaybackStateCompat.ActionPlayPause
                        | PlaybackStateCompat.ActionPause
                        | PlaybackStateCompat.ActionSkipToNext
                        | PlaybackStateCompat.ActionSkipToPrevious
                        | PlaybackStateCompat.ActionStop);

            stateBuilder.SetState(state, position, 0, SystemClock.ElapsedRealtime());
            if (state == PlaybackStateCompat.StateError)
                stateBuilder.SetErrorMessage(errorMessage);
            CurrentSession?.SetPlaybackState(stateBuilder.Build());
            OnStatusChanged?.Invoke(CurrentSession, state);

            //Used for backwards compatibility
            if ((Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
                && (CurrentSession?.RemoteControlClient == null
                || (bool) !CurrentSession?.RemoteControlClient.Equals(typeof(RemoteControlClient)))) return;

            RemoteControlClient remoteControlClient = (RemoteControlClient)CurrentSession?.RemoteControlClient;

            RemoteControlFlags flags = RemoteControlFlags.Play
                                       | RemoteControlFlags.Pause
                                       | RemoteControlFlags.PlayPause 
                                       | RemoteControlFlags.FastForward;

            remoteControlClient?.SetTransportControlFlags(flags);
            
        }
        private void UpdatePlaybackState(int state)
        {
            if (mediaSessionCompat == null || mediaPlayer == null)
                return;

            try
            {
                PlaybackStateCompat.Builder stateBuilder = new PlaybackStateCompat.Builder()
                    .SetActions(
                        PlaybackStateCompat.ActionPause |
                        PlaybackStateCompat.ActionPlay |
                        PlaybackStateCompat.ActionPlayPause |
                        PlaybackStateCompat.ActionSkipToNext |
                        PlaybackStateCompat.ActionSkipToPrevious |
                        PlaybackStateCompat.ActionStop
                    )
                    .SetState(state, Position, 1.0f, SystemClock.ElapsedRealtime());

                mediaSessionCompat.SetPlaybackState(stateBuilder.Build());

                //Used for backwards compatibility
                if (Build.VERSION.SdkInt < BuildVersionCodes.Lollipop)
                {
                    if (mediaSessionCompat.RemoteControlClient != null && mediaSessionCompat.RemoteControlClient.Equals(typeof(RemoteControlClient)))
                    {
                        RemoteControlClient remoteControlClient = (RemoteControlClient)mediaSessionCompat.RemoteControlClient;

                        RemoteControlFlags flags = RemoteControlFlags.Play
                            | RemoteControlFlags.Pause
                            | RemoteControlFlags.PlayPause
                            | RemoteControlFlags.Previous
                            | RemoteControlFlags.Next
                            | RemoteControlFlags.Stop;

                        remoteControlClient.SetTransportControlFlags(flags);
                    }
                }

                OnStatusChanged(EventArgs.Empty);

                if (state == PlaybackStateCompat.StatePlaying || state == PlaybackStateCompat.StatePaused)
                {
                    StartNotification();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine (ex);
            }
        }
Example #13
0
        public static async void UpdateChromecastNotification(string title, string body, bool isPaused, string poster, long time, long duration)
        {
            try {
                //new Android.Support.V4.Media.Session.MediaControllerCompat.
                var builder = new AndroidX.Core.App.NotificationCompat.Builder(Application.Context);
                builder.SetContentTitle(title);
                builder.SetContentText(body);
                builder.SetAutoCancel(false);

                builder.SetSmallIcon(Resource.Drawable.round_cast_white_48dp2_4);
                builder.SetOngoing(true);

                var context = MainActivity.activity.ApplicationContext;
                if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
                {
                    var channelId = $"{PkgName}.general";
                    var channel   = new NotificationChannel(channelId, "General", NotificationImportance.Default);

                    NotManager.CreateNotificationChannel(channel);

                    builder.SetChannelId(channelId);
                    //https://m.media-amazon.com/images/M/MV5BMTczNTI2ODUwOF5BMl5BanBnXkFtZTcwMTU0NTIzMw@@._V1_UX182_CR0,0,182,268_AL_.jpg
                    var bitmap = await GetImageBitmapFromUrl(poster);                    //"https://m.media-amazon.com/images/M/MV5BMTczNTI2ODUwOF5BMl5BanBnXkFtZTcwMTU0NTIzMw@@._V1_UX182_CR0,0,182,268_AL_.jpg");

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

                    var stateBuilder = new PlaybackStateCompat.Builder()
                                       .SetActions(PlaybackStateCompat.ActionSeekTo | PlaybackStateCompat.ActionPause | PlaybackStateCompat.ActionPlay | PlaybackStateCompat.ActionStop)
                                       .SetState(
                        isPaused ? PlaybackStateCompat.StatePaused : PlaybackStateCompat.StatePlaying,
                        time, 1f, SystemClock.ElapsedRealtime()
                        );

                    mediaSession.SetPlaybackState(stateBuilder.Build());
                    mediaSession.SetFlags(MediaSessionCompat.FlagHandlesMediaButtons | MediaSessionCompat.FlagHandlesTransportControls);
                    mediaSession.SetMetadata(new Android.Support.V4.Media.MediaMetadataCompat.Builder()
                                                                                                   //.PutString(MediaMetadata.MetadataKeyArtist, "title")
                                                                                                   //.PutString(MediaMetadata.MetadataKeyTitle, "genre")
                                             .PutLong(MediaMetadata.MetadataKeyDuration, duration) //Negative duration means the duration is unknown
                                                                                                   // .PutString(MediaMetadata.MetadataKeyArt, "https://homepages.cae.wisc.edu/~ece533/images/peppers.png")
                                             .Build());
                    builder.SetColor(Android.Graphics.Color.Black.ToArgb());                       // THIS IS VERY IMPORTANT FOR THE APPERANCE OF THE SEEKBAR IN THE NOTIFICATION
                    builder.SetColorized(true);

                    mediaSession.Active = true;

                    //	mediaSession.SetMetadata(new Android.Support.V4.Media.MediaMetadataCompat() { Description = new Android.Support.V4.Media.MediaDescriptionCompat() { } })

                    List <string> actionNames = new List <string>()
                    {
                        "-30s", isPaused ? "Play" : "Pause", "+30s", "Stop"
                    };
                    List <int> sprites = new List <int>()
                    {
                        Resource.Drawable.netflixGoBack128, isPaused ? Resource.Drawable.netflixPlay128v2 : Resource.Drawable.netflixPause128v2, Resource.Drawable.netflixGoForward128, Resource.Drawable.netflixStop128v2
                    };
                    List <string> actionIntent = new List <string>()
                    {
                        "goback", isPaused ? "play" : "pause", "goforward", "stop"
                    };                                                                                                                                 // next

                    for (int i = 0; i < sprites.Count; i++)
                    {
                        var _resultIntent = new Intent(context, typeof(ChromeCastIntentService));
                        _resultIntent.PutExtra("data", actionIntent[i]);
                        var _pending = PendingIntent.GetService(context, 2337 + i,
                                                                _resultIntent,
                                                                PendingIntentFlags.UpdateCurrent
                                                                );

                        builder.AddAction(new AndroidX.Core.App.NotificationCompat.Action(sprites[i], actionNames[i], _pending));
                    }

                    builder.SetStyle(new NotificationCompat.MediaStyle().SetMediaSession(mediaSession.SessionToken).SetShowActionsInCompactView(0, 1, 2));                     // NICER IMAGE
                }

                builder.SetContentIntent(GetCurrentPending("openchrome"));

                try {
                    NotManager.Notify(CHROME_CAST_NOTIFICATION_ID, builder.Build());
                }
                catch (Exception _ex) {
                    print("EX NOTTIFY;; " + _ex);
                }
            }
            catch (Exception _ex) {
                error(_ex);
            }
        }