警报管理器本地通知 - 打开通知时如何打开特定页面? [英] Alarm manager local notification - how to open a specific page when open notification?

查看:29
本文介绍了警报管理器本地通知 - 打开通知时如何打开特定页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了警报管理器,用户可以在其中设置日期和时间,他将在该日期/时间收到本地通知.我面临的问题是,当我打开通知时,我不知道如何导航到特定页面.这是我的 xamarin.android 代码.我使用的是 xamarin 表单.

I have used alarm manager where user set date and time and he will get local notification on that date/time. The problem I am facing is, that I don't know how to navigate to specific a page when I open notification. Here is my xamarin.android code. I am using xamarin forms.

 public class LocalNotificationService : ILocalNotificationService
    {
        int _notificationIconId { get; set; }
        readonly DateTime _jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        internal string _randomNumber;

        public void LocalNotification(string title, string body, int id, DateTime notifyTime)
        {

            //long repeateDay = 1000 * 60 * 60 * 24;
            long repeateForMinute = 60000;
            long totalMilliSeconds = (long)(notifyTime.ToUniversalTime() - _jan1st1970).TotalMilliseconds;
            if (totalMilliSeconds < JavaSystem.CurrentTimeMillis())
            {
                totalMilliSeconds = totalMilliSeconds + repeateForMinute;
            }

            var intent = CreateIntent(id);
            var localNotification = new ContactDetail();
            localNotification.Title = title;
            localNotification.Body = body;
            localNotification.Id = id;
            localNotification.TimeSchedule = notifyTime.ToString();

            if (_notificationIconId != 0)
            {
                localNotification.IconId = _notificationIconId;
            }
            else
            {
                localNotification.IconId = Resource.Drawable.af;
            }

            var serializedNotification = SerializeNotification(localNotification);
            intent.PutExtra(ScheduledAlarmHandler.LocalNotificationKey, serializedNotification);

            Random generator = new Random();
            _randomNumber = generator.Next(100000, 999999).ToString("D6");

            var pendingIntent = PendingIntent.GetBroadcast(Application.Context, Convert.ToInt32(_randomNumber), intent, PendingIntentFlags.Immutable);
            var alarmManager = GetAlarmManager();
            alarmManager.SetRepeating(AlarmType.RtcWakeup, totalMilliSeconds, repeateForMinute, pendingIntent);
        }

        public void Cancel(int id)
        {

            var intent = CreateIntent(id);
            var pendingIntent = PendingIntent.GetBroadcast(Application.Context, Convert.ToInt32(_randomNumber), intent, PendingIntentFlags.Immutable);
            var alarmManager = GetAlarmManager();
            alarmManager.Cancel(pendingIntent);
            var notificationManager = NotificationManagerCompat.From(Application.Context);
            notificationManager.CancelAll();
            notificationManager.Cancel(id);
        }

        public static Intent GetLauncherActivity()
        {

            var packageName = Application.Context.PackageName;
            return Application.Context.PackageManager.GetLaunchIntentForPackage(packageName);
        }


        private Intent CreateIntent(int id)
        {

            return new Intent(Application.Context, typeof(ScheduledAlarmHandler))
                .SetAction("LocalNotifierIntent" + id);
        }

        private AlarmManager GetAlarmManager()
        {

            var alarmManager = Application.Context.GetSystemService(Context.AlarmService) as AlarmManager;
            return alarmManager;
        }

        private string SerializeNotification(ContactDetail notification)
        {

            var xmlSerializer = new XmlSerializer(notification.GetType());

            using (var stringWriter = new StringWriter())
            {
                xmlSerializer.Serialize(stringWriter, notification);
                return stringWriter.ToString();
            }
        }
    }

    [BroadcastReceiver(Enabled = true, Label = "Local Notifications Broadcast Receiver")]
    public class ScheduledAlarmHandler : BroadcastReceiver
    {

        public const string LocalNotificationKey = "LocalNotification";

        public override void OnReceive(Context context, Intent intent)
        {
            var extra = intent.GetStringExtra(LocalNotificationKey);
            var notification = DeserializeNotification(extra);
            //Generating notification
            var builder = new NotificationCompat.Builder(Application.Context)
                .SetContentTitle(notification.Title)
                .SetContentText(notification.Body)
                .SetSmallIcon(notification.IconId)
                .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Ringtone))
                .SetAutoCancel(true);

            var resultIntent = LocalNotificationService.GetLauncherActivity();
            resultIntent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);
            var stackBuilder = Android.Support.V4.App.TaskStackBuilder.Create(Application.Context);
            stackBuilder.AddNextIntent(resultIntent);

            Random random = new Random();
            int randomNumber = random.Next(9999 - 1000) + 1000;

            var resultPendingIntent =
                stackBuilder.GetPendingIntent(randomNumber, (int)PendingIntentFlags.Immutable);
            builder.SetContentIntent(resultPendingIntent);
            // Sending notification
            var notificationManager = NotificationManagerCompat.From(Application.Context);
            notificationManager.Notify(randomNumber, builder.Build());
        }

        private ContactDetail DeserializeNotification(string notificationString)
        {

            var xmlSerializer = new XmlSerializer(typeof(ContactDetail));
            using (var stringReader = new StringReader(notificationString))
            {
                var notification = (ContactDetail)xmlSerializer.Deserialize(stringReader);
                return notification;
            }
        }
    }

这是我的视图模型代码

 public class LocalNotificationPageViewModel : INotifyPropertyChanged
    {

        Command _saveCommand;
        public Command SaveCommand
        {
            get
            {
                return _saveCommand;
            }
            set
            {
                SetProperty(ref _saveCommand, value);
            }
        }

        bool _notificationONOFF;
        public bool NotificationONOFF
        {
            get
            {
                return _notificationONOFF;
            }
            set
            {
                SetProperty(ref _notificationONOFF, value);
                Switch_Toggled();
            }
        }

        void Switch_Toggled()
        {

            if (NotificationONOFF == false)
            {

                MessageText = string.Empty;
                SelectedTime = DateTime.Now.TimeOfDay;
                SelectedDate = DateTime.Today;
                DependencyService.Get<ILocalNotificationService>().Cancel(0);
            }
        }

        DateTime _selectedDate = DateTime.Today;
        public DateTime SelectedDate
        {
            get
            {
                return _selectedDate;
            }
            set
            {
                SetProperty(ref _selectedDate, value);
            }
        }

        TimeSpan _selectedTime = DateTime.Now.TimeOfDay;
        public TimeSpan SelectedTime
        {
            get
            {
                return _selectedTime;
            }
            set
            {
                SetProperty(ref _selectedTime, value);
            }
        }

        string _messageText;
        public string MessageText
        {
            get
            {
                return _messageText;
            }
            set
            {
                SetProperty(ref _messageText, value);
            }
        }

        public LocalNotificationPageViewModel()
        {
            SaveCommand = new Command(() => SaveLocalNotification());
        }

        void SaveLocalNotification()
        {

            if (NotificationONOFF == true)
            {

                var date = (SelectedDate.Date.Month.ToString("00") + "-" + SelectedDate.Date.Day.ToString("00") + "-" + SelectedDate.Date.Year.ToString());

                var time = Convert.ToDateTime(SelectedTime.ToString()).ToString("HH:mm");

                var dateTime = date + " " + time;

                var selectedDateTime = DateTime.ParseExact(dateTime, "MM-dd-yyyy HH:mm", CultureInfo.InvariantCulture);

                if (!string.IsNullOrEmpty(MessageText))
                {

                    DependencyService.Get<ILocalNotificationService>().Cancel(0);
                    DependencyService.Get<ILocalNotificationService>().LocalNotification("Local Notification", MessageText, 0, selectedDateTime);
                    App.Current.MainPage.DisplayAlert("LocalNotificationDemo", "Notification details saved successfully ", "Ok");

                }
                else
                {
                    App.Current.MainPage.DisplayAlert("LocalNotificationDemo", "Please enter meassage", "OK");
                }

            }
            else
            {
                App.Current.MainPage.DisplayAlert("LocalNotificationDemo", "Please switch on notification", "OK");
            }
        }

        protected bool SetProperty<T>(ref T backingStore, T value,
           [CallerMemberName]string propertyName = "",
           Action onChanged = null)
        {
            if (EqualityComparer<T>.Default.Equals(backingStore, value))
                return false;
            backingStore = value;
            onChanged?.Invoke();
            OnPropertyChanged(propertyName);
            return true;
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
        {
            var changed = PropertyChanged;
            if (changed == null)
                return;
            changed.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

在此之前,我使用了带有 firebase 的推送通知,我可以轻松打开通知并导航到我想要的特定信息,但我不知道如何处理警报管理器通知.

Before this I have used push notification with firebase and I could easily open notification and navigate to specific that I want, but I don't know how to do with alarm manager notification.

推荐答案

你可以试试这个:

LaunchMode.SingleTop 设置为您的 MainActiviy :

set LaunchMode.SingleTop to your MainActiviy :

[Activity(LaunchMode = LaunchMode.SingleTop)]
public class MainActivity:FormsAppCompatActivity

在 MainActiviy 中添加 OnNewIntent 方法:

add the OnNewIntent method in MainActiviy :

protected override void OnNewIntent(Intent intent)
  {
    base.OnNewIntent(intent);
    NavigateTo(intent);
  }

NavigateTo方法中,你可以通过intent.Action或者intent.HasExtra来判断是你的通知:

in the NavigateTo method,you can determine if it is your notification by intent.Action or intent.HasExtra:

void NavigateTo(Intent intent)
{
  //the action and extra you could set in your resultIntent 
  if (intent.Action == "XXXX" && intent.HasExtra("XXXX"))
  {

     Xamarin.Forms.Application.Current.MainPage.Navigation.PushModalAsync(new Page());
  }
}

你也可以使用 MessagingCenterNavigateTo 方法中导航新页面.

and you also could use MessagingCenter in NavigateTo method to navigate a new page.

这篇关于警报管理器本地通知 - 打开通知时如何打开特定页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆