首页 > 解决方案 > Xamarin Device.StartTimer 无法正常工作

问题描述

Xamarin.Form.Device.Timer 的工作方式在设备和平台之间并不一致。试图实现一个计时器,用户必须在 60 秒的时间限制内输入。

尝试了两种方法: 方法 1:当我使用 Device.Timer 等待用户 60 秒让用户输入输入时,当应用程序进入后台(在 iOS 设备上)时计时器停止运行。当应用程序恢复时,它从进入后台的位置开始运行。(代码不包括,它只是一个简单的 Device.Timer 实现)

方法2:为了实现上述目的,我使用生命周期事件来存储应用程序进入后台的时间,并在 Resume 上进行了一些计算并使其连续运行。(包括下面的代码)但是,这种方法在某些设备中也不起作用(经过的时间与 UI 中的时间不一致,或者在某些设备中,当应用程序进入后台时计时器停止,无法调试,因为我没有有这些无法使用的设备)。有没有其他方法可以在 android 和 iOS 平台上实现这一点?

    Constructor(){
        // Timer text binded to UI
        TimerText = "1.00 min";
        StartTimer(60);
    }

    bool stopTimer { get; set; }

    private string timerText;
    public string TimerText
    {
        get => timerText;
        set
        {
            SetProperty(ref timerText, value);
        }
    }


    public void SetTimerText(int secondsCount)
    {
        TimeSpan time = TimeSpan.FromSeconds(secondsCount);
        // Timer Text is binded to a label in UI
        TimerText = time.ToString(@"m\:ss");
    }

    private void StartTimer(int countSeconds)
    {

        SetTimerText(countSeconds);
        IsResendEnable = false;
        _countSeconds = countSeconds;
        stopTimer = true;

        Device.StartTimer(TimeSpan.FromSeconds(1), () =>
        {   
            // Start from 60,..59,.. till 1 and then stop untill Send again is clicked

            _countSeconds--;

            SetTimerText(_countSeconds);

            string[] tokens = TimerText.Split(':');

            if (_countSeconds == 0)
            {
                StopTimer();
                stopTimer = false;
            }
            return stopTimer;
        });

    }

    private void StopTimer()
    {
        stopTimer = false;
        IsResendEnable = true;
        TimerText = "0.00";
    }

    public int TimeLapse = 0;
    public void OnResume()
    {
        TimeSpan TimeDifference = DateTime.Now.Subtract(DeviceTimeBeforeSleep);
        int restartCounter = 60 - (TimeLapse + int.Parse(TimeDifference.Seconds.ToString()));
        if (restartCounter > 0)
        {
            StartTimer(restartCounter);
        }
        else
        {
            StopTimer();
        }
    }

    public void OnSleep()
    {
        //throw new NotImplementedException();
        DeviceTimeBeforeSleep = DateTime.Now;
        TimeLapse = 60 - _countSeconds;
        _countSeconds = 0;
        stopTimer = false;
    }
    
    private async Task ResendCodeCommandExecute(){
        this.StartTimer(60);
    }

标签: androidxamarinxamarin.formsxamarin.androidxamarin.ios

解决方案


推荐阅读