0

I am trying to start a service when my device boots up, but the service never starts.

I have added:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

to AndroidManifest.xml. My BroadcastReceiver looks like this:

[BroadcastReceiver]
[IntentFilter(new[] { Intent.ActionBootCompleted })]
public class BootReceiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        var start = new Intent(context, typeof(AlertSyncService));
        start.AddFlags(ActivityFlags.NewTask);
        context.StartService(start);
    }
}

I have confirmed my service is not the issue (tested by starting the same service on button click - it works fine). The issue is definitely that the BroadcastReceiver is never receiving the event. I've also ensured that I open the app once before rebooting - I saw in a similar question that this is necessary, as apps are installed in a "stopped state".

Does anybody have any ideas what could be causing this not to work? I'm relatively new to this, so highly likely I've missed something obvious!

Thanks

A.Davis
  • 1
  • 1
  • 2
  • Top of my head without see the `logcat` output : `[BroadcastReceiver(Enabled = true)]` Review the testing (via `adb`) section of this answer: https://stackoverflow.com/a/47601952/4984832 – SushiHangover Nov 28 '18 at 22:32
  • @SushiHangover I've done the adb testing, and think this is the issue: `java.lang.RuntimeException: Unable to start receiver md527b6cae80f13bfed8573ffa181fefc60.BootReceiver: java.lang.IllegalStateException: Not allowed to start service Intent { flg=0x10000000 cmp=MyApp.MyApp/md527b6cae80f13bfed8573ffa181fefc60.AlertSyncService }: app is in background uid UidRecord{6ef4e91 u0a6 ...` However, I don't know how to resolve this! Any ideas? I have tried running it with `ContextCompat.StartForegroundService(...)` But this has the same issue. – A.Davis Nov 29 '18 at 18:41
  • https://stackoverflow.com/questions/46445265/android-8-0-java-lang-illegalstateexception-not-allowed-to-start-service-inten – SushiHangover Nov 29 '18 at 20:23

1 Answers1

0

You could try this:

[BroadcastReceiver(Enabled = true, Exported = true, DirectBootAware = true)]
[IntentFilter(new string[] {
    Intent.ActionBootCompleted, Intent.ActionLockedBootCompleted, "android.intent.action.QUICKBOOT_POWERON"
})]
public class BootReceiver: BroadcastReceiver {
    public override void OnReceive(Context context, Intent intent) {
        //Do something
    }
}
navylover
  • 12,383
  • 5
  • 28
  • 41