Защо мога да натискам бутоните си за възпроизвеждане/пауза само веднъж в моето известие за Android?

Създадох известие за моето медийно приложение, което ще позволи на потребителя да пусне/постави на пауза своето аудио. Но в момента те могат да натиснат бутона в известието само веднъж.. Как мога да го накарам, така че потребителят да може непрекъснато да натиска бутона за възпроизвеждане/пауза?

Опитах се просто да направя ново известие в дейността си като начин просто да опресня информацията, но това все още не ми е дало много резултати.

Изграждане на известието

public void Init(DabPlayer Player, bool IntegrateWithLockScreen)
        {
            player = Player;
            var mSession = new MediaSessionCompat(Application.Context, "MusicService");
            mSession.SetFlags(MediaSessionCompat.FlagHandlesMediaButtons | MediaSessionCompat.FlagHandlesTransportControls);
            var controller = mSession.Controller;
            var description = GlobalResources.playerPodcast;

            if (IntegrateWithLockScreen)
            {
                /* SET UP LOCK SCREEN */
                CreateNotificationChannel();

                player.EpisodeDataChanged += (sender, e) =>
                {
                    // Set up an intent so that tapping the notifications returns to this app:
                    Intent intent = new Intent(Application.Context, typeof(MainActivity));
                    Intent playPauseIntent = new Intent(Application.Context, typeof(SecondActivity));
                    // Create a PendingIntent; we're only using one PendingIntent (ID = 0):
                    const int pendingIntentId = 0;
                    const int firstPendingIntentId = 1;
                    PendingIntent firstPendingIntent =
                        PendingIntent.GetActivity(Application.Context, firstPendingIntentId, intent, PendingIntentFlags.OneShot);
                    PendingIntent pendingIntent =
                        PendingIntent.GetActivity(Application.Context, pendingIntentId, playPauseIntent, PendingIntentFlags.OneShot);

                    // Build the notification:
                    var builder = new NotificationCompat.Builder(Application.Context, CHANNEL_ID)
                                  .SetStyle(new Android.Support.V4.Media.App.NotificationCompat.MediaStyle()
                                            .SetMediaSession(mSession.SessionToken)
                                            .SetShowActionsInCompactView(0, 1))
                                  .SetVisibility(NotificationCompat.VisibilityPublic)
                                  .SetContentIntent(firstPendingIntent) // Start up this activity when the user clicks the intent.
                                  .SetDeleteIntent(MediaButtonReceiver.BuildMediaButtonPendingIntent(Application.Context, PlaybackState.ActionStop))
                                  .SetSmallIcon(Resource.Drawable.app_icon) // This is the icon to display
                                  .AddAction(Resource.Drawable.ic_media_pause_dark, "Pause", pendingIntent)
                                  .AddAction(Resource.Drawable.ic_media_play_dark, "Next", pendingIntent)
                                  .SetContentText(GlobalResources.playerPodcast.EpisodeTitle)
                                  .SetContentTitle(GlobalResources.playerPodcast.ChannelTitle);

                    // Finally, publish the notification:
                    var notificationManager = NotificationManagerCompat.From(Application.Context);
                    notificationManager.Notify(NOTIFICATION_ID, builder.Build());                   
                };

                player.EpisodeProgressChanged += (object sender, EventArgs e) =>
                {

                };


            }

И тогава дейността ми изглежда така

[Activity]
    public class SecondActivity : Activity
    {
        DabPlayer player = GlobalResources.playerPodcast;
        EpisodeViewModel Episode;
        DroidDabNativePlayer droid = new DroidDabNativePlayer();
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            if (player.IsReady)
            {
                if (player.IsPlaying)
                {
                    player.Pause();
                    droid.Init(player, true);
                }
                else
                {
                    player.Play();
                    droid.Init(player, true);
                }
            }
            else
            {
                if (player.Load(Episode.Episode))
                {
                    player.Play();
                    droid.Init(player, true);
                }
                else
                {
                    //DisplayAlert("Episode Unavailable", "The episode you are attempting to play is currently unavailable. Please try again later.", "OK");
                }

            }

            Finish();
        }
    }

Също така искам просто да сляза до един бутон и той да превключва между показване на пауза и възпроизвеждане в зависимост от състоянието, ако някой иска да ме насочи в правилната посока и за това.

Всяка помощ се оценява! Благодаря ти!


person Carr O'Connor    schedule 23.07.2019    source източник
comment
Какво имаш предвид, че могат да натиснат play само веднъж? какво се случва втория път? Какъв беше резултатът от опресняването на известието?   -  person Blundell    schedule 23.07.2019
comment
Не реагира на второ кликване. Нищо не се случва, след като го щракнат втори път. Опресняването на известието не ми позволи да мога да щракам върху бутоните отново.   -  person Carr O'Connor    schedule 23.07.2019
comment
В момента там има 2 бутона, които правят едно и също нещо, просто изглеждат различно, но ако щракна върху един от тях, не мога дори да щракна върху другия. Изглежда просто убива взаимодействията с бутоните след първото събитие.   -  person Carr O'Connor    schedule 23.07.2019


Отговори (1)


https://developer.android.com/reference/android/app/PendingIntent

PendingIntents с OneShot могат да се използват само веднъж.

Флаг, показващ, че това PendingIntent може да се използва само веднъж. Ако е зададено, след извикването на send(), то автоматично ще бъде отменено за вас и всеки бъдещ опит за изпращане през него ще бъде неуспешен.

Или използвайте PendingIntent без флагове (за да позволите на потребителя да натисне бутона няколко пъти и да изпрати множество намерения), или използвайте нов идентификатор всеки път, когато поискате PendingIntent, за да позволите бутонът да бъде натискан веднъж всеки път, когато актуализирате известието.

person Blundell    schedule 23.07.2019
comment
Работи като чар! Благодаря ти! - person Carr O'Connor; 23.07.2019