I am trying to plan an auto launch for my app, every day at a given hour. I have a bunch of code which works well as far as my activity is running (in foreground or background) but this stops working when activity is killed (via task manager or forced killed). I searched a lot but nothing helped.
Here is my lightened code :
[BroadcastReceiver(Enabled = true, Exported = true)]
public class AutoWakeUpReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
AutoWakeUpReceiver.SetNextAutoWakeUp(AlarmManager.IntervalDay);
Intent wakeUpIntent = new Intent(context, typeof(MainActivity));
wakeUpIntent.SetFlags(ActivityFlags.ReorderToFront | ActivityFlags.BroughtToFront | ActivityFlags.NewTask);
context.StartActivity(wakeUpIntent);
}
public static void SetNextAutoWakeUp(long delayInMillis)
{
Intent wakeUpIntent = new Intent(AndroidContext.Instance.MainActivity, typeof(AutoWakeUpReceiver));
PendingIntent existing = PendingIntent.GetBroadcast(AndroidContext.Instance.MainActivity, 0, wakeUpIntent, PendingIntentFlags.NoCreate);
existing?.Cancel();
PendingIntent pending = PendingIntent.GetBroadcast(AndroidContext.Instance.MainActivity, 0, wakeUpIntent, PendingIntentFlags.UpdateCurrent);
AlarmManager alarmManager = (AlarmManager)AndroidContext.Instance.MainActivity.GetSystemService(Context.AlarmService);
if (Build.VERSION.SdkInt < BuildVersionCodes.M)
alarmManager.Set(AlarmType.ElapsedRealtimeWakeup, SystemClock.ElapsedRealtime() + delayInMillis, pending);
else
alarmManager.SetAndAllowWhileIdle(AlarmType.ElapsedRealtimeWakeup, SystemClock.ElapsedRealtime() + delayInMillis, pending);
}
}
I also put this in my OnCreate() activity so that the screen unlocks and lights on (works), and to set the first alarm :
protected override void OnCreate(Bundle bundle)
{
this.Window.AddFlags(WindowManagerFlags.TurnScreenOn | WindowManagerFlags.DismissKeyguard | WindowManagerFlags.ShowWhenLocked);
AutoWakeUpReceiver.SetNextAutoWakeUp(0);
}
I tried declaring my receiver in the manifest, but didn't changed anything and I read that Xamarin will do it himself. By the way, I have this problem in all android versions (from 19 to 27), so its not a battery optimization problem. I guess that it's a broadcast problem, but I am not able to make it work after activity's death.
Thanks in advance