JL.
JL.

Reputation: 81292

code running from alarm manager dying after 1 minute

I have some code that should take (roughly) 5 minutes to run. This code should run periodically, so I'm calling it using the built in AlarmManager.

Like this:

public void setAlarm(Context context)
{
    AlarmManager am = (AlarmManager)context.GetSystemService(Context.AlarmService);
    Intent i = new Intent(context, typeof(keyboardservice.alarmreciever));

    PendingIntent pi = PendingIntent.GetBroadcast(context, 0, i, PendingIntentFlags.CancelCurrent);
    am.SetRepeating(AlarmType.ElapsedRealtimeWakeup, 0, 1000 * 60 * 30, pi); // Millisec * Second * Minute
}

As you can see the code should run every 30 minutes.

AlarmService looks something like this :

[BroadcastReceiver(Enabled = true)]
public class alarmreciever : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        Task.Delay(1000 * 300).Wait();
    }
}

I've simplified the code above, but the result is the same the code dies after 1 minute (exactly), like there's some limit.

It doesn't matter if the screen is on or off.

What am I missing?

Upvotes: 0

Views: 63

Answers (2)

JL.
JL.

Reputation: 81292

Solved with :

new Task(() =>
            {

                DoAction(context);
            }).Start();

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1006859

AlarmService looks something like this

That is not a Service. That is a BroadcastReceiver.

What am I missing?

First, your BroadcastReceiver is attempting to tie up the main application thread for five minutes. Even if that were possible, it would be a profoundly bad idea, as that means that your UI would be frozen during those five minutes. But, it is not possible, as a watchdog should terminate your work in the ANR timeout period (10-15 seconds for background work IIRC).

Second, in general, you cannot do anything in the background for more than a minute on Android 8.0+. There are exceptions, notably if you use JobScheduler, where you have ~10 minutes.

If you are sure that your work will be completed in less than 10 minutes, then if your minSdkVersion is 21 or higher, switch to JobScheduler. If your minSdkVersion is below 21, at least on those older devices, have your BroadcastReceiver start a JobIntentService, were you do your five minutes of work in onHandleWork().

Note that I do not know what of this has been Xamarin-ified, as I do not use Xamarin.

Upvotes: 3

Related Questions