Xamarin Forms后台服务,即使应用程序关闭也能同步数据。

问题描述 投票:1回答:1

我想创建一个服务,即使我的应用程序关闭Sqlite和mysql的数据同步在后台运行的。

我已经尝试了一些方法,但无法实现我的目标。

如果有人能给我一个示例应用程序,运行在后台的服务,即使应用程序关闭。

谢谢你

c# xamarin xamarin.forms xamarin.android backgrounding
1个回答
1
投票

如果你想运行你的后台功能,即使你的应用程序关闭后,在一定的时间间隔,我们需要创建一个前台服务。我说的是Android。

首先在Android项目文件夹中创建一个服务类.这里我创建的服务名为SqlService。

  [Service]
    class SqlService : Service
    {
        internal static readonly string CHANNEL_ID = "my_notification_channel";
        internal static readonly int NOTIFICATION_ID = 100;
        public override IBinder OnBind(Intent intent)
        {
            return null;
        }
        /*
         * This service will run until stopped explicitly because we are returning sticky
         */
        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            Toast.MakeText(this, "Service started", ToastLength.Long).Show();
            StartServiceInForeground();
            return StartCommandResult.Sticky;
        }
        /*
         * When our service is to be destroyed, show a Toast message before the destruction.
         */
        public override void OnDestroy()
        {
            base.OnDestroy();
            Toast.MakeText(this, "Syncing stopped", ToastLength.Long).Show();
        }

        void StartServiceInForeground()
        {

            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                var intent = new Intent(this, typeof(MainActivity));

                var channel = new NotificationChannel(CHANNEL_ID, "Service Channel", NotificationImportance.High)
                {
                    Description = "Foreground Service Channel"
                };

                var notificationManager = (NotificationManager)GetSystemService(NotificationService);
                notificationManager.CreateNotificationChannel(channel);
                var pendingIntent = PendingIntent.GetActivity(this, MainActivity.NOTIFICATION_ID, intent, PendingIntentFlags.Immutable);
                var notification = new Notification.Builder(this, CHANNEL_ID)
                .SetContentTitle("My Sql App")
                .SetContentText("Sql Sync is on")
                .SetContentIntent(pendingIntent)
                .SetSmallIcon(Resource.Drawable.sr_notification)                
                .SetOngoing(true)
                .Build();
                 StartForeground(NOTIFICATION_ID, notification);
            }



            Device.StartTimer(TimeSpan.FromSeconds(300),  () =>
            {

                try
                {

                  //.. Do your sql syncing here 

                }

                catch (Exception ex)
                {

                }
                return true;
            });
        }

    }

在你的MainActivity中,你可以通过使用共享项目中的messeging中心调用来启动服务,我们还需要创建一个Notification通道。

在你的 MainActivity

 public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {       
        internal static readonly string CHANNEL_ID = "my_notification_channel";
        internal static readonly int NOTIFICATION_ID = 100;

       protected override void OnCreate(Bundle savedInstanceState)
        {       
            base.OnCreate(savedInstanceState);         
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());
            CreateNotificationChannel();
            loadservice();      
        }




            void CreateNotificationChannel()
        {
            if (Build.VERSION.SdkInt < BuildVersionCodes.O)
            {
                // Notification channels are new in API 26 (and not a part of the
                // support library). There is no need to create a notification 
                // channel on older versions of Android.
                return;
            }

            var channel = new NotificationChannel(CHANNEL_ID, "FCM Notifications", NotificationImportance.Default)
            {
                Description = "Firebase Cloud Messages appear in this channel",
            };
            channel.EnableVibration(true);
            channel.EnableLights(true);

            var notificationManager = (NotificationManager)GetSystemService(NotificationService);
            notificationManager.CreateNotificationChannel(channel);
        }


            private void loadservice()
        {

            MessagingCenter.Subscribe<Object>(this, "StartLongRunningTaskMessage", (sender) => {
                Intent myIntent = new Intent(this, typeof(LocationService));
                this.StartService(myIntent);
            });

            MessagingCenter.Subscribe<Object>(this, "StopLongRunningTaskMessage", (sender) => {
                Intent myIntent = new Intent(this, typeof(LocationService));
                this.StopService(myIntent);
            });
        }
}

现在,你可以从你的共享项目中启动服务,比如,让我们说一个按钮点击。

  private async void Sync_Clicked(object sender, EventArgs e)
    {
     MessagingCenter.Send<Object>(new Object(), "StartLongRunningTaskMessage");     
    }

我们也可以停止服务的另一个按钮点击一样。

  private async void Sync_Clicked(object sender, EventArgs e)
        {
         MessagingCenter.Send<Object>(new Object(), "StopLongRunningTaskMessage");      
        }

返回,如果你有任何疑问。

© www.soinside.com 2019 - 2024. All rights reserved.