在我的应用程序中,我有在指定时间内发生的通知(类似警报),我需要在用户退出应用程序后删除此通知。这可能吗?
AlarmReceiver.cs
using Android.Content;
using Android.App;
using Android.Graphics;
namespace XamarinWorkTimer.Droid
{
[BroadcastReceiver]
public class AlarmReceiver : BroadcastReceiver
{
NotificationManager manager;
public override void OnReceive(Context context, Intent intent)
{
string message = intent.GetStringExtra("message");
string title = intent.GetStringExtra("title");
Intent notIntent = new Intent(context, typeof(MainActivity));
PendingIntent contentIntent = PendingIntent.GetActivity(context, 0, notIntent, PendingIntentFlags.CancelCurrent);
manager = NotificationManager.FromContext(context);
var style = new Notification.BigTextStyle();
style.BigText(message);
int resourceId = Resource.Drawable.icon;
var wearableExtender = new Notification.WearableExtender()
.SetBackground(BitmapFactory.DecodeResource(context.Resources, resourceId))
;
//Generate a notification with just short text and small icon
var builder = new Notification.Builder(context)
.SetPriority((int)NotificationPriority.Max)
.SetVisibility(NotificationVisibility.Public)
.SetDefaults(NotificationDefaults.All)
.SetCategory(Notification.CategoryAlarm)
.SetContentIntent(contentIntent)
.SetSmallIcon(Resource.Drawable.icon)
.SetContentTitle(title)
.SetContentText(message)
.SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis())
.SetAutoCancel(true);
var notification = builder.Build();
manager.Notify(0, notification);
}
}
}
AndroidReminderService.cs
using Android.Content;
using Android.App;
using Xamarin.Forms;
using Android.OS;
[assembly: Dependency(typeof(XamarinWorkTimer.Droid.AndroidReminderService))]
namespace XamarinWorkTimer.Droid
{
public class AndroidReminderService : IReminderService
{
public void Remind(int seconds, string title, string message)
{
Intent alarmIntent = new Intent(Forms.Context, typeof(AlarmReceiver));
alarmIntent.PutExtra("message", message);
alarmIntent.PutExtra("title", title);
PendingIntent pendingIntent = PendingIntent.GetBroadcast(Forms.Context, 0, alarmIntent, PendingIntentFlags.UpdateCurrent);
AlarmManager alarmManager = (AlarmManager)Forms.Context.GetSystemService(Context.AlarmService);
alarmManager.Set(AlarmType.ElapsedRealtimeWakeup, SystemClock.ElapsedRealtime() + seconds * 1000, pendingIntent);
}
}
}
答案 0 :(得分:1)
PendingIntent pendingIntent;
...
public void OnDestroy()
{
base.OnDestroy();
pendingIntent.Cancel();
}
点击此处:https://developer.xamarin.com/guides/android/application_fundamentals/activity_lifecycle/了解有关生命周期的更多信息