gpt4 book ai didi

android - 删除通知 xamarin

转载 作者:行者123 更新时间:2023-11-29 01:17:21 26 4
gpt4 key购买 nike

在我的应用程序中,我有在指定时间发生的通知(类似于警报),我需要在用户退出应用程序后删除此通知。这可能吗?

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);
}

}
}

最佳答案

 PendingIntent pendingIntent;


...


public void OnDestroy()
{
base.OnDestroy();

pendingIntent.Cancel();
}

在这里查看:https://developer.xamarin.com/guides/android/application_fundamentals/activity_lifecycle/有关生命周期的更多信息

关于android - 删除通知 xamarin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38759318/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com