我在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分钟后触发此通知。
任何代码都赞赏。
答案 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方法中。如果你需要,我也有一些示例代码。