运行 一名 android 工人,当 phone 靴子不起作用时

Running an android Worker when phone boots doesn't work

我有一个工作正常的工人。我想在 phone 启动时启动它。我使用了一个应该监听系统 booted_completed 事件的广播接收器,但是这个广播接收器从未被调用过。

在我的清单中,我添加了这个权限:<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

这是我的广播接收器:

[BroadcastReceiver(Enabled = true)]
[IntentFilter(new[] { Android.Content.Intent.ActionBootCompleted })]
public class BootBroadcastReceiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        //Notify that the broadcast receiver is launched
        await AndroidNotificationService.NotifyUser("Device boot", "The device is booting", 11, context);
        OneTimeWorkRequest notifWork = new OneTimeWorkRequest.Builder(typeof(Services.Background.NotificationsBackgroundWorker))
            .Build();
        WorkManager.Instance.Enqueue(notifWork);
    }
}

但这并没有帮助。当我重新启动我的设备时,接收器永远不会启动。我正在 android 9.

上测试这个

事实证明,从 API 26 Android 开始限制对广播接收器的访问。我克服这个问题的方法是在我的广播接收器中创建一个前台服务,它在后台完成我想要的工作或者启动我的 WorkManager。

 [BroadcastReceiver]
[IntentFilter(new [] { Intent.ActionBootCompleted }, Priority = (int)IntentFilterPriority.HighPriority)]
public class BootBroadcastReceiver : BroadcastReceiver
{
    public async override void OnReceive(Context context, Intent intent)
    {
        context.StartForegroundServiceCompat<AfterBootSyncService>();
    }
}

这里是扩展方法的实现StartForegroundServiceCompat:

    public static void StartForegroundServiceCompat<T>(this Context context, Bundle args = null) where T : Service
    {
        var intent = new Intent(context, typeof(T));
        if (args != null)
        {
            intent.PutExtras(args);
        }

        if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
        {
            context.StartForegroundService(intent);
        }
        else
        {
            context.StartService(intent);
        }
    }

当我这样做时,我的广播接收器中的代码被正常调用。