【发布时间】:2018-01-25 03:23:31
【问题描述】:
(我在这里问是因为我没有在 Xamarin 论坛上获得帮助)我正在使用此代码创建警报:
Intent alarmIntent = new Intent(context, typeof(AlarmReceiver));
notificationClickIntent = PendingIntent.GetActivity(context, 0, new Intent(), 0);
pendingIntent = PendingIntent.GetBroadcast(context, 0, alarmIntent, PendingIntentFlags.UpdateCurrent);
am = (AlarmManager)Android.App.Application.Context.GetSystemService(Context.AlarmService);
DateTime setTime = new DateTime(temp.Ticks + offset); //temp is the current time where seconds field = 0
if ((int)Build.VERSION.SdkInt >= 21) //my device enters this case
{
AlarmManager.AlarmClockInfo info = new AlarmManager.AlarmClockInfo(setTime.Ticks, notificationClickIntent);
am.SetAlarmClock(info, pendingIntent);
}
else {
am.SetExact(AlarmType.RtcWakeup, setTime.Ticks, notificationClickIntent);
}
在调用该代码之前,我的班级确保这些代码也已执行:
ComponentName receiver = new ComponentName(context, Java.Lang.Class.FromType(typeof(AlarmReceiver)));
PackageManager pm = context.PackageManager;
pm.SetComponentEnabledSetting(receiver, ComponentEnabledState.Enabled, ComponentEnableOption.DontKillApp);
Intent alarmIntent = new Intent(context, typeof(AlarmReceiver));
notificationClickIntent = PendingIntent.GetActivity(context, 0, new Intent(), 0);
pendingIntent = PendingIntent.GetBroadcast(context, 0, alarmIntent, PendingIntentFlags.UpdateCurrent);
am = (AlarmManager)Android.App.Application.Context.GetSystemService(Context.AlarmService);
这是我的接收器:
[BroadcastReceiver (Process = ":remote")]
public class AlarmReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
Console.WriteLine("alarm fired");
Toast.MakeText(context, "Received intent!", ToastLength.Short).Show();
}
}
好的,Xamarin 正确地注册了接收器。我知道这一点,因为如果我给 AlarmClockInfo 一个不正确的刻度值(一个超出 DateTime 刻度范围的值),警报会立即响起并调用我的 OnReceive 方法。但是,当我给它一个刻度值时,比如比当前时间提前一分钟,警报不会响起。也许时间错了?...似乎不是这样,因为我已经记录了系统下一次预定警报的时间,并且它会在我设置它的同时报告回来。有什么想法吗?
编辑:所以我已经有一个 android 应用程序可以正确执行所有这些操作。当我将它转换为 Xamarin 和 C# 时,它不再起作用。
【问题讨论】:
-
@JonDouglas 谢谢,但这是 Android Java。所以我已经有一个可以正确执行所有这些的 android 应用程序。当我将其转换为 Xamarin 和 C# 时,它不再起作用。
-
那么请把它包含在你的原始帖子中。
-
@sadelbrid
setTime.Ticks的值是多少?即temp.Ticks&offset的值是多少? -
为什么 Xamarin 论坛如此休眠?
标签: xamarin xamarin.android broadcastreceiver alarmmanager