在 Xamarin 中一段时间​​后发送本地通知 Android

Sending Local Notifications after some time in Xamarin Android

我在 Visual Studio 2015 中使用 Xamarin。我想每隔 x 分钟发送一次本地通知,如何实现这个目标? 我将通知构建为

       // Instantiate the builder and set notification elements:
        Notification.Builder builder = new Notification.Builder(this)
            .SetContentTitle("Alert")
            .SetContentText("Time to go")
            .SetSmallIcon(Resource.Drawable.notification_alert)
        .SetDefaults(NotificationDefaults.Sound);

        // Build the notification:
        Notification notification = builder.Build();

        // Get the notification manager:
        NotificationManager notificationManager =
        GetSystemService(Context.NotificationService) as NotificationManager;

        // Publish the notification:
        const int notificationId = 0;
        notificationManager.Notify(notificationId, notification);

现在我想在每 x 分钟后触发此通知。

感谢任何代码。

NotificationCompat 无法设置为自行重复,您需要 AlarmManager 才能实现您的目标。下面的一些示例代码每 10 分钟发出一次警报:

设置重复闹钟

var alarmTime = Calendar.Instance; // Alarm Start Time
alarmTime.Add(Calendar.Second, 30); // Addding 30 seconds to ensure alarm is not in past

var intent = new Intent(Android.App.Application.Context, typeof(ScheduledAlarmHandler));
var pendingIntent = PendingIntent.GetBroadcast(Android.App.Application.Context, 0, intent, PendingIntentFlags.CancelCurrent);
var alarmManager = Android.App.Application.Context.GetSystemService(Context.AlarmService) as AlarmManager;

var interval = 10 * 60 * 1000 ; // 10 Minutes - in Milliseconds

alarmManager.SetRepeating(AlarmType.RtcWakeup, alarmTime.TimeInMillis, interval, pendingIntent); 

使用 BroadCastReceiver 接收警报

[BroadcastReceiver]
class ScheduledAlarmHandler : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        Console.WriteLine("ScheduledAlarmHandler", "Starting service @" + SystemClock.ElapsedRealtime());

        // Your App code here - start an Intentservice if needed;
    }
}

您已经掌握了发送本地通知的逻辑,因此请从 BroadCastReceiver 中调用该方法。但是,您在这里完成操作的时间有限(我相信最多 10 秒)所以如果您需要任何后台刷新活动、API 调用等,最好启动 IntentServiceWakefulIntentService 在 OnReceive 方法中。如果您需要,我还有一些示例代码。