Xamarin AlarmManager not firing when app sleeps

主宰稳场 提交于 2021-01-29 21:32:59

问题


I have following code to fire an alarm at exact time. When my app goes to sleep/background, Alarm does not FIRE, however as soon as I unlock my phone, then it fires right away.

    Intent i = new Intent(this, typeof(MyReceiver));
    i.PutExtra("Speaker", txtSpeaker.Text);
    PendingIntent pi = PendingIntent.GetBroadcast(this, 0, i, 0);

    string _date = DateTime.Today.ToString("MM-dd-yyyy")  ;
    string _time = tpick.Hour + ":" + tpick.Minute;
    DateTime scheduleAt = Convert.ToDateTime(_date).Add(TimeSpan.Parse(_time));
    DateTimeOffset dateOffsetValue = DateTimeOffset.Parse(scheduleAt.ToString());
    var millisec = dateOffsetValue.ToUnixTimeMilliseconds();

    AlarmManager alarmManager = (AlarmManager)GetSystemService(AlarmService);
    alarmManager.SetExact(AlarmType.RtcWakeup, millisec, pi);

and here is my Receiver Class...

[BroadcastReceiver]
public class MyReceiver : BroadcastReceiver
{
    public async override void OnReceive(Context context, Intent intent)
    {


        Console.WriteLine("FIRED");

        String result = intent.Extras.GetString("Speaker");

        Toast.MakeText(context, "Alarm Ringing!", ToastLength.Short).Show();

    }
}

回答1:


If the App is running on API 23 or newer, you might want to look into using the SetExactAndAllowWhileIdle method. According to the documentation it appears to me that this method will ignore whether the Device is in some low-power state or doze is enabled.



来源:https://stackoverflow.com/questions/64635627/xamarin-alarmmanager-not-firing-when-app-sleeps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!