Xamarinf.forms android Task.run () causes app to freeze when in background after a few minutes

My goal is to create a task that runs while the app is running , it doesn't matter if the app is in the foreground / background or if the screen is off.

I have this simple code in 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();
        }
    }
}

      

App freezes after ~ 10 minutes - tried it 3 times when the app was in the background + screen off after 5 minutes.

it worked well for the first few minutes

Tested on android Samsung S7

what am I doing wrong? does the same problem exist for IOS?

+3


source to share


1 answer


In general, mobile apps cannot run in the background (see Activity Lifecycle https://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle ). On iOS, you can't even think about what to expect in some of the strict cases that are allowed (like audio player). On Android it is a little less strict and you can use the Background Service https://developer.android.com/training/run-background-service/index.html .



-1


source







All Articles