每隔几分钟在移动应用程序中执行一次功能,无论 foreground/background

Execute function in mobile app every few minutes, regardless of foreground/background

我正在尝试 运行 Xamarin Forms 的函数,特别是每隔几分钟 Android。可悲的是,围绕这个的文档即使不是含糊不清也没什么。除其他事项外,它还向我介绍了(已弃用的)FireBase 作业调度程序。

目前,我试过这个:

Android
MainActivity.cs

[Activity(Label = "SolutionName", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize )]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            Xamarin.FormsMaps.Init(this, savedInstanceState);
            LoadApplication(new App());

            //StartService(new Intent(this, typeof(PeriodicService)));

            var alarmIntent = new Intent(this, typeof(BackgroundReceiver));

            var pending = PendingIntent.GetBroadcast(this, 0, alarmIntent, PendingIntentFlags.UpdateCurrent);

            var alarmManager = GetSystemService(AlarmService).JavaCast<AlarmManager>();
            alarmManager.Set(AlarmType.ElapsedRealtime, SystemClock.ElapsedRealtime() + 3 * 1000, pending);
        }
    }
}

BroadcastReceiver.cs

[BroadcastReceiver]
    public class BackgroundReceiver : BroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            PowerManager pm = (PowerManager)context.GetSystemService(Context.PowerService);
            PowerManager.WakeLock wakeLock = pm.NewWakeLock(WakeLockFlags.Partial, "BackgroundReceiver");
            wakeLock.Acquire();

            MessagingCenter.Send<object, string>(this, "UpdateLabel", "Hello from Android");

            wakeLock.Release();
        }
    }

主要 HomePage.xaml

<Label Text="Welcome to Xamarin Forms!" 
    x:Name="BackgroundServiceLabel"
    VerticalOptions="Center" 
    HorizontalOptions="Center" />

HomePage.xaml.cs

public HomePage()
    {
        InitializeComponent();
        InitializeGeofences();
        GetData();

        MessagingCenter.Subscribe<object, string>(this, "UpdateLabel", (s, e) =>
        {
            Device.BeginInvokeOnMainThread(() =>
        {
            BackgroundServiceLabel.Text = e;
        });
    });
}

这段代码没有 运行,也没有任何错误。我做错什么了吗? 有任何修复吗? 有替代路线吗?

感谢您花时间阅读本文。

简短的回答是“你做不到”。 长答案是: 强制系统周期性地执行某事不是一个好的设计 新的和新的 Android OS 版本有更多的限制。 最好将您的应用程序设计为根据某些系统或用户事件执行某些逻辑。

您可以使用 WorkManager API 安排您的任务 要启动一些过程,您可以使用推送通知 API

有时候我们必须强制系统执行一些任务 为此,我们可以再次使用 ForegroundService 但它应该是您的“最后手段”。