xamarinf.forms android Task.run()导致应用程序在几分钟后在后台冻结

时间:2017-04-27 18:48:36

标签: xamarin xamarin.ios xamarin.android xamarin.forms

我的目标是创建一个任务,只要应用程序正在运行就运行,如果应用程序位于前景/后台或屏幕已关闭,则无法运行。

我在xamarin.forms中有这个简单的代码MainPage.cs:

public partial class MainPage : ContentPage
{
    int _num = 0;
    Label l = new Label();
    Button b;
    public MainPage()
    {
        InitializeComponent();

        l.TextColor = Color.Black;
        l.Text = "AAAA";
        b = new Button();
        b.Clicked += B_Clicked;

        StackLayout s = new StackLayout();
        s.Children.Add(l);
        s.Children.Add(b);

        Content = s;

        Task.Run(() => incNumberTaskWork());
    }

    private void B_Clicked(object sender, EventArgs e)
    {
        l.Text = _num.ToString();
    }

    void incNumberTaskWork()
    {
        while (_num < 0xffffffff)
        {
            _num++;
            Task.Delay(1000).Wait();
        }
    }
}

应用程序在大约10分钟后冻结 - 尝试了3次,当应用程序在后台+屏幕关闭5分钟后。

前几分钟它运作良好

在Android三星S7上检查它

我在做错了什么? IOS也存在同样的问题吗?

1 个答案:

答案 0 :(得分:-1)

通常,移动应用无法在后台运行(请参阅活动生命周期https://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle)。在iOS上,你甚至无法在一些允许的严格情况下(如音频播放器)考虑这种期望。在Android上它的严格程度要低一些,你可以使用后台服务https://developer.android.com/training/run-background-service/index.html