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

时间:2016-07-14 05:02:29

标签: c#-4.0 xamarin.android android-service

我在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分钟后触发此通知。

任何代码都赞赏。

1 个答案:

答案 0 :(得分:0)

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调用等,最好开始IntentService或{{1}在OnReceive方法中。如果你需要,我也有一些示例代码。