仅在打开并运行应用程序时如何在后台运行方法? [英] How to run a method in the background only when app is open and running?

查看:170
本文介绍了仅在打开并运行应用程序时如何在后台运行方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

应用程序打开并运行后,我希望后台进程检查数据库并根据数据库中的数据进行更新.我想每隔一分钟进行一次检查.我只希望在应用程序位于前台并在用户看来时发生这种情况.

Once the app is open and running I would like a background process to check a database and to make an update depending on the data in the database. I would like to make this check every one minute. I only want this to happen when the app is in the foreground and in view of the user.

有人可以给我一些有关我该如何做的建议吗?我想我可以从这里调用方法,但是我不确定该怎么做.另外,我不知道如何停止,即使我需要手动取消/停止该过程.当应用程序不在前台时会取消自身,并在应用程序回到前台时重新启动吗?

Can someone give me some suggestions as to how I do this? I assume I can call a method from here but I'm not sure how to do this. Also I do not know how to stop or even if I need to manually cancel / stop the process. Would it cancel itself when the app is not in the foreground and restart when the app came back into the foreground?

public partial class App : Application
{

   protected override void OnStart()
   {
      App.DB.InitData();
      MainPage = new Japanese.MainPage();
   }

但是我需要在另一个线程上运行它吗?如果可以,我该怎么做.

But do I need to make this run on a different thread and if so how could I do that.

对不起,如果我的问题不清楚.请询问,如果没有意义,我可以更新.

Sorry if my question is not clear. Please ask and I can update if it doesn't make sense.

推荐答案

我们在表单应用程序中所做的工作是利用System.Diagnostics中可用的Device.Timer和Stopwatch类以及Xamarin.Forms来创建一个非常通用的托管计时器,我们可以使用Xamarin.Forms中的onStart,onSleep和onResume方法与之交互.

What we did in our forms application was to make use of the Device.Timer and the Stopwatch class that available in System.Diagnostics, and Xamarin.Forms to create a very generic managed timer that we could interact with using the onStart, onSleep and onResume methods in Xamarin.Forms.

此特定解决方案不需要任何特定于平台的逻辑,并且设备计时器和秒表不受UI限制.

This particular solution doesn't require any special platform specific logic, and the device timer and stopwatch are non UI blocking.

using Xamarin.Forms;
using System;
using System.Linq;
using System.Diagnostics;

namespace YourNamespace
{
    public partial class App : Application
    {
        private static Stopwatch stopWatch = new Stopwatch();
        private const int defaultTimespan = 1;

        protected override void OnStart()
        {
            // On start runs when your application launches from a closed state, 

            if (!stopWatch.IsRunning)
            {
                stopWatch.Start();
            }

            Device.StartTimer(new TimeSpan(0, 0, 1), () =>
            {
                // Logic for logging out if the device is inactive for a period of time.

                if (stopWatch.IsRunning && stopWatch.Elapsed.Minutes >= defaultTimespan)
                {
                    //prepare to perform your data pull here as we have hit the 1 minute mark   

                        // Perform your long running operations here.

                        Device.InvokeOnMainThread(()=>{
                            // If you need to do anything with your UI, you need to wrap it in this.
                        });

                    stopwatch.Restart();
                }

                // Always return true as to keep our device timer running.
                return true;
            });
        }

        protected override void OnSleep()
        {
            // Ensure our stopwatch is reset so the elapsed time is 0.
            stopWatch.Reset();
        }

        protected override void OnResume()
        {
            // App enters the foreground so start our stopwatch again.
            stopWatch.Start();
        }
    }
}





提供有关上述解决方案如何逐步工作的背景信息:

To give some context as to how the above solution works step by step:

应用程序从关闭状态开始,"OnStart()"方法创建我们的Device.Timer,它每秒滴答一次.它还会启动我们的秒表,计时最多一分钟.

The application starts from a closed state and the 'OnStart()' method creates our Device.Timer that ticks every second. It also starts our stopwatch that counts upto a minute.

当应用程序进入后台时,如果我们要将"false"值传递到Device.StartTimer()操作中,则此时会点击"OnSleep"方法,它将不会再次启动.因此,我们只需要重置秒表即可为该应用再次打开做好准备.

When the app goes into the background it hits the 'OnSleep' method at this point if we were to pass a 'false' value into our Device.StartTimer() action it would not start up again. So instead we simply reset our stopwatch ready for when the app is opened again.

当应用回到前台时,它会点击"OnResume"方法,该方法只是启动现有的秒表.

When the app comes back into the foreground it hits the 'OnResume' method, which simply starts the existing stopwatch.

2018

即使在2018年,此答案仍然有其优点,但主要针对非常特殊的情况.即使在Xamarin.Forms中,也有更好的特定于平台的方法来复制此功能.考虑到用户的活动/不活动,上述内容仍然是一段时间后执行任务的平台不可知的方式.

This answer still has some merits even in 2018, but mainly for very specific situations. There are better platform specific ways to replicate this functionality even in Xamarin.Forms. The above still remains a platform agnostic way to perform a task after a period of time, taking into account user activity/inactivity.

这篇关于仅在打开并运行应用程序时如何在后台运行方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆