Xamarin.Android: Как добавить уникальное намерение для каждого уведомления - PullRequest
0 голосов
/ 14 октября 2019

Я добавляю Intent s в Android.Support.V4.App.NotificationCompat.Builder, но Extras не передается в переопределение OnNewIntent, и кажется, что параметр всегда один и тот же Intent. Идея заключается в foreach уведомлении в списке уведомлений пользователя. Мое приложение создает пользовательский объект уведомления, а затем создает Bundle и Intent.

//custom notification class just contains the information for notifications public class CustomNotification { public string _noteType { get; set; } public string _noteText { get; set; } public string _noteLink { get; set; } public int _noteIndex { get; set; } }

    public void SendNotifications(List<CustomNotification> notificationList)
    {
        try
        {
            var _ctx = Android.App.Application.Context;
            int _noteCount = 0;
            foreach (var note in notificationList)
            {
                //I'm instantiating a new Intent foreach so not sure why 
                // each would not have it's own Extras
                var resultIntent = new Intent(_ctx, typeof(MainActivity));
                var valuesForActivity = new Bundle();
                valuesForActivity.PutInt(MainActivity.COUNT_KEY, _count);
                //this will always be the same string when it hits OnNewIntent in MainActivity
                valuesForActivity.PutString("URL", note._noteLink);
                //this will always be the same number when it hits OnNewIntent in MainActivity
                valuesForActivity.PutInt("NoteNumber", _noteCount);
                resultIntent.PutExtras(valuesForActivity);

                var resultPendingIntent = PendingIntent.GetActivity(_ctx, 0, resultIntent, PendingIntentFlags.UpdateCurrent);

                resultIntent.AddFlags(ActivityFlags.SingleTop);

                // Build the notification:
                var builder = new Android.Support.V4.App.NotificationCompat.Builder(_ctx, MainActivity.CHANNEL_ID)
                              .SetAutoCancel(true) // Dismiss the notification from the notification area when the user clicks on it
                              .SetContentIntent(resultPendingIntent) // I'm passing the Intent here.. the rest of the builder vars work
                              .SetContentTitle(note._noteType) // Set the title
                              .SetNumber(_count) // Display the count in the Content Info
                              .SetSmallIcon(2130837590) // This is the icon to display
                              .SetContentText(note._noteText);


                MainActivity.NOTIFICATION_ID++;

                var notificationManager = Android.Support.V4.App.NotificationManagerCompat.From(_ctx);
                notificationManager.Notify(MainActivity.NOTIFICATION_ID, builder.Build());

                _noteCount++;
            }

        }
        catch
        {

        }
    }


    //this is inside MainActivity.cs
    protected override void OnNewIntent(Intent intent)
    {
        string url = "";
        int noteCount = 0;


        if (intent != null)
        {
            //this is always the same url
            url = intent.Extras.GetString("URL");
            //this is always the same int
            noteCount = intent.Extras.GetInt("NoteNumber");
        }

        try
        {
            switch (_viewPager.CurrentItem)
            {
                case 0:
                    _fm1.LoadCustomUrl(url);
                    break;
                case 1:
                    _fm2.LoadCustomUrl(url);
                    break;
                case 2:
                    _fm3.LoadCustomUrl(url);
                    break;
                case 3:
                    _fm4.LoadCustomUrl(url);
                    break;
                case 4:
                    _fm5.LoadCustomUrl(url);
                    break;
            }
        }
        catch
        {

        }
        base.OnNewIntent(intent);
    }

Я ожидаю, что когда я передам Intent в конструктор, он вернет уникальное значение, но одна и та же строка всегда возвращает независимо от того, какое уведомление я нажимаю. Я прошел через код, так как каждое уведомление создается, и в каждый Intent передается уникальная строка. Что я тут не так сделал?

1 Ответ

1 голос
/ 14 октября 2019

var resultPendingIntent = PendingIntent.GetActivity (_ctx, 0, resultIntent, PendingIntentFlags.UpdateCurrent);

Extra будет обновлено до Extra последнего входящего намерения ,, так что вы получитетоже самоеЕсли вам необходимо получить правильные дополнительные данные для каждого уведомления, есть два метода:

1.При определении намерений вам также необходимо различать намерения! Вы можете добавить код под намерением, например:

resultIntent.SetData(Android.Net.Uri.Parse("custom://" + SystemClock.CurrentThreadTimeMillis()));

2. var resultPendingIntent = PendingIntent.GetActivity(_ctx, 0, resultIntent, PendingIntentFlags.UpdateCurrent); изменить на:

var resultPendingIntent = PendingIntent.GetActivity(_ctx,  MainActivity.NOTIFICATION_ID, resultIntent, PendingIntentFlags.UpdateCurrent);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...