警报管理器警报触发时如何运行代码

时间:2018-08-22 20:31:54

标签: java android xamarin push-notification xamarin.android

我正在尝试找出当警报管理器警报触发时如何运行一些代码。我目前可以安排警报,现在,当警报触发时,我正在发送广播,并且我有广播接收器来接听。问题是,当用户通过从最近的应用程序中刷出应用程序来关闭应用程序时,我的广播接收器停止了,因此,即使发送了广播,也没有接收器来接收它。如何从警报中直接运行代码?

这是我现在使用的代码,用于在特定时间创建通知:

创建警报:

 alarmManager.SetExactAndAllowWhileIdle(AlarmType.ElapsedRealtimeWakeup, SystemClock.ElapsedRealtime() + ((long)(App.checkInTimes[i].TimeOfDay.TotalSeconds - DateTime.Now.TimeOfDay.TotalSeconds) * 1000), PendingIntent.GetBroadcast(Android.App.Application.Context, 0, new Intent("android.intent.action.CREATE_CHECKIN_NOTIFICATION"), PendingIntentFlags.UpdateCurrent));

然后由广播接收器创建通知:

[IntentFilter(new[] { "android.intent.action.CREATE_CHECKIN_NOTIFICATION" })]
public class NotificationReceiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        //Send Check In Notification
        //Setup notification
        Notification.Builder builder = new Notification.Builder(Android.App.Application.Context);
        builder.SetContentTitle("Please Check In Now");
        builder.SetContentText("Tap here to check in");
        builder.SetSmallIcon(Resource.Drawable.exclamationPoint);
        builder.SetPriority(2);
        long[] pattern = { 1000, 1000, 1000, 1000 };
        builder.SetVibrate(pattern);
        builder.SetLights(Android.Graphics.Color.Red, 1500, 1500);
        Intent launchIntent = new Intent(Android.App.Application.Context, typeof(CheckInScreen));
        PendingIntent pendingIntent = PendingIntent.GetActivity(Android.App.Application.Context, 1, launchIntent, PendingIntentFlags.UpdateCurrent);
        builder.SetContentIntent(pendingIntent);

        //Build notification
        Notification notification = builder.Build();
        notification.Flags = NotificationFlags.AutoCancel;

        //Get Notification Manager
        NotificationManager notificationManager = Android.App.Application.Context.GetSystemService(Context.NotificationService) as NotificationManager;
        //Publish Notification
        notificationManager.Notify(0, notification);}

1 个答案:

答案 0 :(得分:0)

来自this

  

问题是您的BroadcastReceiver没有[BroadcastReceiver]属性。

看看您的代码,这正是问题所在。您缺少上述属性。

尝试添加

[BroadcastReceiver]

在类定义之前。