设备屏幕关闭时 UWP 后台任务 HttpClient 失败 [英] UWP Background Task HttpClient fails when device screen is off

查看:18
本文介绍了设备屏幕关闭时 UWP 后台任务 HttpClient 失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一款专为手机设计的 UWP 应用.它旨在与在本地家庭网络上运行的服务器同步数据.此同步可能需要相当长的时间,因此后台任务不是同步数据的最佳位置;它可能需要超过我分配的 30 秒.然而,这个想法是使用带有计时器触发器的后台任务;它会调用服务器检查是否有任何更新要使用,然后弹出一个 toast 通知,询问它是否可以在前台运行以执行同步.

I'm working on a UWP app designed for phones. It's designed to sync data with a server running on your local home network. This syncing might take quite some time so a background task isn't the best place to sync the data; it'll probably take more than the 30 seconds I'm allotted. The idea, however, is to use a background task with a timer trigger; it'll call the server to check if there are any updates to consume and then pop up a toast notification asking if it can run in the foreground to perform the synchronization.

代码效果很好...如果屏幕打开.但是如果屏幕关闭,那么我永远不会收到任何通知.起初我以为 timertrigger 没有触发,但我在它运行时记录下来,果然,每 15 分钟准时运行一次.我更深入地研究它,它失败了.具体来说,它在网络调用上失败了;HttpClient.GetAsync,出现以下错误:

The code works great... if the screen is on. But if the screen is turned off, then I never get any notifications. At first I thought the timertrigger wasn't triggering, but I logged whenever it ran and sure enough, ir ran every 15 minutes on time. I looked deeper into it, and it's failing. Specifically, it's failing on the network call; HttpClient.GetAsync, with the following error:

"The text associated with this error code could not be found.\r\n\r\nA connection with the server could not be established\r\n"

现在我检查了服务器;它正在运行.我打开屏幕,代码突然又开始工作了.我已将触发器设置为仅在未计量的连接可用时运行:

Now I checked the server; it's running. I turn the screen on and the code suddenly works again. I've set up the trigger to only run when an unmetered connection is available:

    var status = await BackgroundExecutionManager.RequestAccessAsync();
    if(status.In(BackgroundAccessStatus.DeniedBySystemPolicy, BackgroundAccessStatus.DeniedByUser))
    {
        return;
    }

    var builder = new BackgroundTaskBuilder();
    builder.Name = Constants.BackgroundTaskName;
    builder.SetTrigger(new TimeTrigger(15, false));
    builder.AddCondition(new SystemCondition(SystemConditionType.FreeNetworkAvailable));
    BackgroundTaskRegistration task = builder.Register();

所以我会认为计时器仅在 Wifi 可用时触发.但是当我实际使用此代码执行 HTTP Get 时:

So I would think that the timer only gets triggered when the Wifi is available. But then when I actually perform the HTTP Get using this code:

    async protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args)
    {
        if (BackgroundWorkCost.CurrentBackgroundWorkCost == BackgroundWorkCostValue.High)
            return;
        if (!NetworkInterface.GetIsNetworkAvailable())
            return;
        base.OnBackgroundActivated(args);
        if (args.TaskInstance.Task.Name == Constants.BackgroundTaskName)
        {
            var cancel = new CancellationTokenSource();
            args.TaskInstance.Canceled += (s, e) =>
            {
                cancel.Cancel();
                cancel.Dispose();
            };
            var deferral = args.TaskInstance.GetDeferral();
            try
            {
                HttpClient client = GetClient();
                var response = await client.GetAsync(ConstructUrl(client.BaseAddress, "updates"), cancel.Token);
                var info = await ParseHttpResponse<UpdateInformation>(response);     
            }
            catch { }
            finally
            {
                deferral.Complete();
            }
        }

现在有趣的是,NetworkInterface.GetIsNetworkAvailable() 返回true",告诉我有可用的网络.但是,当我拨打电话时,我收到无法建立与服务器的连接".我不知道我在这里做错了什么.

Now the funny thing is, NetworkInterface.GetIsNetworkAvailable() returns "true", telling me there's a network available. But still, when I make the call, I get "A connection with the server could not be established". I have no idea what I'm doing wrong here.

有什么想法吗?

推荐答案

您很可能需要在后台任务注册中指定IsNetworkRequested",以便网络在连接待机(这发生在屏幕关闭).

It is very likely that you are required to specify "IsNetworkRequested" on your background task registration in order for the network to be functional during connected standby (which occurs while the screen is off).

请参阅此处的文档:https://docs.microsoft.com/en-us/uwp/api/Windows.ApplicationModel.Background.BackgroundTaskBuilder

这篇关于设备屏幕关闭时 UWP 后台任务 HttpClient 失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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