我使用了警报管理器,用户在其中设置日期和时间,他将在该日期/时间获得本地通知。我面临的问题是,当我打开通知时,我不知道如何导航到特定页面。这是我的 xamarin.android 代码。我正在使用xamarin表格。
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一起使用,可以轻松地打开通知并导航至所需的特定对象,但是我不知道如何处理警报管理器通知。
答案 0 :(得分:0)
您可以尝试以下方法:
将 LaunchMode.SingleTop 设置为您的 MainActiviy :
[Activity(LaunchMode = LaunchMode.SingleTop)]
public class MainActivity:FormsAppCompatActivity
在MainActiviy中添加 OnNewIntent 方法:
protected override void OnNewIntent(Intent intent)
{
base.OnNewIntent(intent);
NavigateTo(intent);
}
在 NavigateTo 方法中,您可以通过intent.Action
或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());
}
}
,您还可以在 NavigateTo 方法中使用MessagingCenter来浏览新页面。